这是一个涉及Python中的条件正则表达式的问题:Python的条件正则表达式
我想匹配字符串
match(1)="a"
match(2)="b"
match(3)="c"
而且还匹配字符串" a"
与
match(1)="a"
match(2)=""
match(3)=""
以下代码几乎是这样做的,问题是在第一种情况下match(1)="a"
bu t在第二种情况下,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的)
你说得对 - 这是仅有的两个案例。正如我所希望的那样工作。关键是有“?”在匹配组(\ w?)内部,以便匹配该字母,或者不匹配任何内容。谢谢! – Mike 2010-06-28 16:14:23
@Mike,不客气 - 总是乐于帮忙! – 2010-06-28 16:43:47