这是一道python条件正则表达式题:
我想匹配字符串 "abc"
和
match(1)="a"
match(2)="b"
match(3)="c"
还要匹配字符串 "a"
和
match(1)="a"
match(2)=""
match(3)=""
下面的代码几乎就是这样做的,问题是在第一种情况下 match(1)="a"
但在第二种情况下,match(4)="a"
(不是所需的match(1)
)。
事实上,如果您使用 for g in re.search(myre,teststring2).groups():
遍历所有组,您将得到 6 个组(不是预期的 3 个)。
import re
import sys
teststring1 = "abc"
teststring2 = " a"
myre = '^(?=(\w)(\w)(\w))|(?=\s{2}(\w)()())'
if re.search(myre,teststring1):
print re.search(myre,teststring1).group(1)
if re.search(myre,teststring2):
print re.search(myre,teststring2).group(1)
有什么想法吗? (注意这是针对 Python 2.5 的)
最佳答案
也许……:
import re
import sys
teststring1 = "abc"
teststring2 = " a"
myre = '^\s{0,2}(\w)(\w?)(\w?)$'
if re.search(myre,teststring1):
print re.search(myre,teststring1).group(1)
if re.search(myre,teststring2):
print re.search(myre,teststring2).group(1)
在这两种情况下,这确实会如您所愿地给出 a
,但在您未显示的其他情况下,它可能与您想要的方式不匹配(例如,前面没有空格,或空格 < em> 和 之后超过一个字母,所以匹配字符串的总长度是 != 3
...但我只是猜测你不 在这种情况下需要匹配...?)
关于Python 条件正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3130209/