下面是Python正则表达式。 ?:
的含义是什么?表达总体上做了什么?它如何匹配MAC地址,例如“00:07:32:12:ac:de:ef
”?
re.compile(([\dA-Fa-f]{2}(?:[:-][\dA-Fa-f]{2}){5}), string)
答案 0 :(得分:8)
它(?:...)
表示一组非捕获分组括号。
通常,当您在正则表达式中编写(...)
时,它会“捕获”匹配的材料。当您使用非捕获版本时,它不会捕获。
在正则表达式与特定字符串匹配后,您可以使用regex包中的方法获取re
匹配的各个部分。
这个正则表达式如何匹配MAC地址“00:07:32:12:ac:de:ef”?
这与你最初提出的问题不同。但是,正则表达式部分是:
([\dA-Fa-f]{2}(?:[:-][\dA-Fa-f]{2}){5})
最外面的一对括号正在捕捉括号;当你成功地对字符串使用正则表达式时,它们所包围的内容将可用。
[\dA-Fa-f]{2}
部分匹配数字\d
)或十六进制数字A-Fa-f]
,在{2}
对中,后跟非捕获分组匹配的材料是冒号或破折号(:
或-
),后跟另一对十六进制数字,整数重复5次。
p = re.compile(([\dA-Fa-f]{2}(?:[:-][\dA-Fa-f]{2}){5}))
m = p.match("00:07:32:12:ac:de:ef")
if m:
m.group(1)
最后一行应打印字符串“00:07:32:12:ac:de”,因为这是第一组6对十六进制数字(在字符串中总共七对中)。事实上,外部分组括号是多余的,如果省略,m.group(0)
将起作用(它甚至可以与它们一起工作)。如果您需要匹配7对,那么您将5更改为6.如果您需要拒绝它们,那么您将锚点放入正则表达式中:
p = re.compile(^([\dA-Fa-f]{2}(?:[:-][\dA-Fa-f]{2}){5})$)
插入符^
匹配字符串的开头;美元$
匹配字符串的结尾。使用5,这与您的样本字符串不匹配。用6代替5,它会匹配你的字符串。
答案 1 :(得分:6)
在?:
中使用(?:...)
会使组在替换期间无法捕获。在找到它时没有任何意义。
您的RegEx意味着
r"""
( # Match the regular expression below and capture its match into backreference number 1
[\dA-Fa-f] # Match a single character present in the list below
# A single digit 0..9
# A character in the range between “A” and “F”
# A character in the range between “a” and “f”
{2} # Exactly 2 times
(?: # Match the regular expression below
[:-] # Match a single character present in the list below
# The character “:”
# The character “-”
[\dA-Fa-f] # Match a single character present in the list below
# A single digit 0..9
# A character in the range between “A” and “F”
# A character in the range between “a” and “f”
{2} # Exactly 2 times
){5} # Exactly 5 times
)
"""
希望这有帮助。
答案 2 :(得分:0)
(?:...)
表示非预防组。该小组将不会被捕获。