我正在嘗試http://docs.python.org/library/re.html給出的例子,用於組編號和匹配。非常簡單,(.+) \1
應該匹配由空格分隔的兩段相同的文本,並以the the
作爲示例。但是,Python的正則表達式不搜索組編號
re.search('(.+) \1','the the')
返回None
。
我正在使用re
版本2.2.1。
我正在嘗試http://docs.python.org/library/re.html給出的例子,用於組編號和匹配。非常簡單,(.+) \1
應該匹配由空格分隔的兩段相同的文本,並以the the
作爲示例。但是,Python的正則表達式不搜索組編號
re.search('(.+) \1','the the')
返回None
。
我正在使用re
版本2.2.1。
您可能需要逃避你逃跑或使用原始字符串。 例如
re.search('(.+) \\1', 'the the')
或
re.search(r'(.+) \1', 'the the')
看到相同的頁面的例子在raw字符串表示部分。
'\1'
是'\x01'
。也許你的意思是'(.+) \\1'
或r'(.+) \1'
。
我會建議使用命名組這樣的:
(?P=name)
因此,在這種情況下,我會建議使用命名模式和這樣做:
re.search('(?P<first_match>.+) (?P=first_match)', 'the the')
很好的第一個答案。 – 2011-06-15 18:28:40