如何 return 整个非拉丁字符串匹配重复模式,例如 AAB 或 ABB

How to return whole non-latin strings matching a reduplication pattern, such as AAB or ABB

我正在处理非拉丁字符的字符串。 我想匹配具有重复模式的字符串,例如 AAB、ABB、ABAB 等。 我尝试了以下代码:

import re

patternAAB = re.compile(r'\b(\w)\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)\w\b')
match = patternAAB.search(rawtext)
if match:
    print(match.group(1))

如何匹配模式和 return 整个匹配字符串?

# Ex. 哈哈笑 
# string matches AAB pattern so my code returns 哈 
# but not the entire string

留言:

error: cannot refer to an open group at position 7

告诉你 </code> 指的是周围有括号的组,因为它的左括号在前。您要反向引用的组是编号 2,因此此代码有效:</p> <pre><code>import re rawtext = 'abc 哈哈笑 def' patternAAB = re.compile(r'\b((\w)\w)\b') match = patternAAB.findall(rawtext) print(match)

match 中的每个项目都有两个组:

[('哈哈笑', '哈')]

I also found this method, but didn't work for me:

你也离这里很近。您可以使用 match.group(0) 来获得完整匹配,而不仅仅是括号中的一组。所以这段代码有效:

import re

rawtext = 'abc 哈哈笑 def'

patternAAB = re.compile(r'\b(\w)\w\b')
match = patternAAB.search(rawtext)
if match:
    print(match.group(0))   # 哈哈笑