我正在尝试匹配“任何不是.(句点)的连续相同字符链”
比如说,我有:
line = '....xooo......'
如果我这样做,
就会这样。
match in re.findall(r'[^\.]{2,}', line)
match返回"xooo"。
相反,我只想要"ooo",这是一串相同字符的序列。
我该怎么做?
re.search(r'(([^.])\2{1,})', line).group(1)
说明:
"(([^.])\2{1,})"
1st Capturing group (([^.])\2{1,})
2nd Capturing group ([^.])
Negated char class [^.] matches any character except:
. The character .
\2 1 to infinite times [greedy] Matches text saved in the 2nd capturing group
>>> line = '....xooo...xx..yyyyy.'
>>> map(lambda t: t[0], re.findall(r"(([^.])\2+)", line))
# ['ooo', 'xx', 'yyyyy']
line = '....xooo......aaaa...'
import re
print [whole for whole, _ in re.findall("(([^.])\\2+)", line)]
输出
['ooo', 'aaaa']
([^.])
匹配除了 .
以外的任何字符,并将其捕获为一组。 \\2
指代内部捕获的组,该组是由 ([^.])
匹配的字符,而 +
表示至少出现一次。因此,它匹配 ooo
。
aaaaaa...
和 bbbbb...
这样的东西。反向引用功能允许匹配非正则集;也就是说,为了使它像上面那样简洁,我们已经离开了正则表达式的领域,而你想让它更短。 :) - Kaz