簡體   English   中英

Python Regex:匹配由一個其他單詞完全分隔的任何重復單詞

[英]Python Regex: match any repeated words that are separated by exactly one other word

我遇到了這個問題,我需要使用正則表達式來查找由另一個單詞分隔的重復單詞。

因此,如果:

"all in all"將返回: "all"

"good good good"將返回: Null (同一個詞不是另一個詞)

我試過了:

p = re.compile(r'(\b\w+\b)\s\w+\s\1')
m = p.findall('all in all day in and day out bit by bit good good good')

print(m)

這將返回['all', 'bit', 'good'] ,但我只希望它返回['all','bit']

提前致謝!

您只需要在初始捕獲組之后立即為單詞添加否定前瞻,以確保您的正則表達式無法匹配(例如) good good

import re

p = re.compile(r'(\b\w+\b)(?!\s\1\b)\s\w+\s\1\b')
m = p.findall('all in all day in and day out bit by bit good good good')

print(m)

輸出:

['all', 'bit']

如果要包含重疊匹配項,請將整個正則表達式設為正向預測(感謝 @ggorlen):

p = re.compile(r'(?=(\b\w+\b)(?!\s\1\b)\s\w+\s\1\b)')
m = p.findall('foo bar foo bar foo')

輸出:

['foo', 'bar', 'foo']

如果您還需要刪除重復的匹配項,請轉換為set並返回list

p = re.compile(r'(?=(\b\w+\b)(?!\s\1\b)\s\w+\s\1\b)')
m = list(set(p.findall('foo bar foo bar foo')))
print(m)

輸出:

['foo', 'bar']

不需要正則表達式; 正常的編程結構可以很好地處理此類問題。 編寫一個循環並添加一個條件:

s = 'all in all day in and day out bit by bit good good good'

words = s.split()
result = []

for i in range(len(words) - 2):
    if words[i] == words[i+2] and words[i] != words[i+1]:
        result.append(words[i])

print(result) # ['all', 'bit']

暫無
暫無

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

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