簡體   English   中英

如何返回匹配重復模式的整個非拉丁字符串,例如 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)\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

消息:

error: cannot refer to an open group at position 7

告訴你\\1指的是周圍有括號的組,因為它的左括號在前。 您要反向引用的組是 2 號,因此此代碼有效:

import re

rawtext = 'abc 哈哈笑 def'

patternAAB = re.compile(r'\b((\w)\2\w)\b')
match = patternAAB.findall(rawtext)
print(match)

match每個項目都有兩個組:

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

我也找到了這種方法,但對我不起作用:

你也離這里很近。 您可以使用match.group(0)獲得完整匹配,而不僅僅是括號中的組。 所以這段代碼有效:

import re

rawtext = 'abc 哈哈笑 def'

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM