我正在处理非拉丁字符的字符串。我想用重复模式匹配字符串,例如 AAB、ABB、ABAB 等。我尝试了以下代码:
import re
patternAAB = re.compile(r'\b(\w)\1\w\b')
match = patternAAB.findall(rawtext)
print(match)
但是,它只返回匹配字符串的第一个字符。我知道这是因为第一个 \w 周围的捕获括号而发生的。
我试图在整个匹配块周围添加捕获括号,但 Python 给出了
error: cannot refer to an open group at position 7
我也找到了这种方法,但对我不起作用:
patternAAB = re.compile(r'\b(\w)\1\w\b')
match = patternAAB.search(rawtext)
if match:
print(match.group(1))
如何匹配模式并返回整个匹配字符串?
# Ex. 哈哈笑
# string matches AAB pattern so my code returns 哈
# but not the entire string