【问题标题】:More pythonic regex parse更多 pythonic 正则表达式解析
【发布时间】:2011-12-12 23:59:18
【问题描述】:
有没有比做更pythonic的方式:
parsedStr=origStr[compiledRegex.match(origStr).start():compiledRegex.match(origStr).end())
例如,假设我的原始字符串是“The cat said hi”,而我编译的正则表达式是“The.*said”,我会提取文本“The cat said”
上面的代码看起来很丑,但我就是这样做的
【问题讨论】:
标签:
python
regex
string
parsing
match
【解决方案1】:
在匹配对象上使用 group 方法:
>>> import re
>>> origStr = "The cat said hi"
>>> compiledRegex = re.compile('The.*said')
>>> compiledRegex.match(origStr).group()
'The cat said'
【解决方案2】:
这对你有用吗?
instancesFound = compiledRegex.findall(origStr)
if instancesFound:
parsedStr = parsedParts[0]
【解决方案3】:
我是这样写的:
search = re.compile(r'^The.*said').search
match = search(input)
if match:
match = match.group(0)
如果input 是“猫说我的名字”,match 将是“猫说”。
如果input 是“猫从来没有提到我的名字”,那么match 将是None。
我真的很喜欢 Python 可以编译正则表达式并在一行中将感兴趣的特定方法分配给变量。