import re a='abcabc' b=re.search( r '(\d)abc(?(1)\d|abc)', a ) print(b) #为何匹配失败? a='3abcabc'也是如此! 查了下(?(1)\d|abc) 的意思:如果编号为 1 的组匹配到字符,则需要匹配\d ,否则需要匹配 abc. 这里的 1 匹配到字符是指 c 后面匹配到字符呢还是 a 前面匹配到数字字符?
If Clause (?(1)\d|abc) Evaluate the condition below and proceed accordingly (1) checks whether the 1st capturing group matched when it was last attempted If condition is met, match the following regex \d \d matches a digit (equal to [0-9]) Else match the following regex abc abc matches the characters abc literally (case sensitive)