【发布时间】:2016-01-22 19:02:23
【问题描述】:
我正在阅读《用 Python 自动化无聊的东西》一书。在第 7 章,在项目实践中:strip() 的正则表达式版本,这是我的代码(我使用 Python 3.x):
def stripRegex(x,string):
import re
if x == '':
spaceLeft = re.compile(r'^\s+')
stringLeft = spaceLeft.sub('',string)
spaceRight = re.compile(r'\s+$')
stringRight = spaceRight.sub('',string)
stringBoth = spaceRight.sub('',stringLeft)
print(stringLeft)
print(stringRight)
else:
charLeft = re.compile(r'^(%s)+'%x)
stringLeft = charLeft.sub('',string)
charRight = re.compile(r'(%s)+$'%x)
stringBoth = charRight.sub('',stringLeft)
print(stringBoth)
x1 = ''
x2 = 'Spam'
x3 = 'pSam'
string1 = ' Hello world!!! '
string2 = 'SpamSpamBaconSpamEggsSpamSpam'
stripRegex(x1,string1)
stripRegex(x2,string2)
stripRegex(x3,string2)
这是输出:
Hello world!!!
Hello world!!!
Hello world!!!
BaconSpamEggs
SpamSpamBaconSpamEggsSpamSpam
所以,我的 strip() 正则表达式版本几乎可以作为原始版本使用。在原始版本中,无论您传入“Spam”、“pSam”、“mapS”、“Smpa”,输出始终为“BaconSpamEggs”... 那么如何在 Regex 版本中解决这个问题???
【问题讨论】:
-
嗯,正则表达式并不神秘。所以你遇到的问题是你失去了对代码流的控制。
-
什么是“原版”?
-
“原始版本”是本书第 6 章中解释的 strip() 默认方法。示例: spam = 'SpamSpamBaconSpamEggsSpamSpam') 输入: spam.strip('Spam') 或 spam.strip('Smap') 或 spam.strip('pSam') ...输出始终为: BaconSpamEggs跨度>
-
我正在尝试解决同样的问题。完全理解“if”部分,但无法得到“else”。对于 %s 和 %x,re.compile 中的 % 符号是什么意思?