Python 元字符和反斜杠在这里做什么?
我正在从一些网站学习正则表达式,我在理解元字符的用法和原始字符串中反斜杠的用法时遇到了一些困难Python 元字符和反斜杠在这里做什么?,python,regex,Python,Regex,我正在从一些网站学习正则表达式,我在理解元字符的用法和原始字符串中反斜杠的用法时遇到了一些困难 import re pattern = r"(.+) \1" match = re.match(pattern, "word word") if match: print ("Match 1") match = re.match(pattern, "?! ?!") if match: print ("Match 2") match = re.match(pattern
import re
pattern = r"(.+) \1"
match = re.match(pattern, "word word")
if match:
print ("Match 1")
match = re.match(pattern, "?! ?!")
if match:
print ("Match 2")
match = re.match(pattern, "abc cde")
if match:
print ("Match 3")
我的主要疑问是这里使用了(++)和反斜杠。如果不是1而是2,那么输出是什么?我知道+的意思是“一次或多次重复”。当你这样做时:
r"(.+) \1"
表示\1
应与第一组捕获的内容完全匹配。它不匹配“abc cde”
,因为第一组捕获了abc
,所以它就像是在匹配这个:re.match(r'abc abc',text)
。
这将回调引用组
例如,您需要匹配以相同字母开头和结尾的文本:
import re
pattern = r"(\w).+\1"
match = re.match(pattern, "ABA") # OK
match = re.match(pattern, "ABC") # NO
另一个示例匹配以3个字母开头并以该字母结尾的文本,顺序相反
import re
pattern = r"(\w)(\w)(\w)\3\2\1"
re.match(pattern, 'ABCCBA') # OK
re.match(pattern, 'ABCCBC') # NO
注意:您只能反向引用一个捕获组,这意味着这是无效的(?:.+)\1
,因为
第一个组将匹配并且不会捕获任何内容,因此您无法反向引用它
编辑
- 匹配一次或多次的
,需要至少出现一次+
匹配零次或多次*
ca+t
匹配cat、caat、caaat
:匹配c
,后跟至少一个a
或多个t
ca+t
matchct、cat、caaaat
:matchesc
后跟零个或多个a
,后跟t\1
是捕获组1的反向引用,该组1是(.+)
元字符的作用是什么。请指定。请检查我的编辑,希望这件事弄清楚