要禁止字符串中任何位置含有捕获组的字符,可以使用负向前瞻断言来实现。具体的正则表达式如下所示:
import re
pattern = r"(?!.*\(.*)"
string1 = "abc"
string2 = "ab(cdef)"
string3 = "ab(c(d)ef)"
match1 = re.search(pattern, string1)
match2 = re.search(pattern, string2)
match3 = re.search(pattern, string3)
print(match1) #
print(match2) # None
print(match3) # None
在这个正则表达式中,(?!.*\(.*)
表示负向前瞻断言,用来匹配任何位置上不包含捕获组的字符。如果字符串中包含捕获组的字符,则匹配失败,返回None。否则,匹配成功,返回一个Match对象。
在上述示例代码中,string1
中没有捕获组的字符,所以匹配成功;string2
和string3
中都包含捕获组的字符,所以匹配失败,返回None。