更多pythonic正则表达式解析

时间:2011-10-22 01:34:56

标签: python regex string parsing match

是否有更多的pythonic方式而不是:

 parsedStr=origStr[compiledRegex.match(origStr).start():compiledRegex.match(origStr).end())

对于exampile假设我的原始字符串是“猫说你好”,我编译的正则表达式是“。*说”我会拉文本“猫说”

上面的代码看起来很难看,但这就是我一直在做的事情

3 个答案:

答案 0 :(得分:1)

在匹配对象上使用方法:

>>> import re
>>> origStr = "The cat said hi"
>>> compiledRegex = re.compile('The.*said')
>>> compiledRegex.match(origStr).group()
'The cat said'

答案 1 :(得分:0)

这对你有用吗?

instancesFound = compiledRegex.findall(origStr)
if instancesFound:
    parsedStr = parsedParts[0]

答案 2 :(得分:0)

以下是我写的方式:

search = re.compile(r'^The.*said').search
match = search(input)
if match:
    match = match.group(0)

如果input是“猫说我的名字”,match将是“猫说”。

如果input是“猫从未提及我的名字”,match将为None

我非常喜欢Python可以编译正则表达式并将特定感兴趣的方法分配给一行中的变量。