要捕获特殊字符的正则表达式,可以使用转义字符 "" 来转义这些特殊字符。以下是几个常见特殊字符的正则表达式和代码示例:
import re
text = "This is a (test)"
match = re.search(r"\(", text)
if match:
print("找到括号")
else:
print("未找到括号")
import re
text = "This is a [test]"
match = re.search(r"\[", text)
if match:
print("找到方括号")
else:
print("未找到方括号")
import re
text = "This is a {test}"
match = re.search(r"\{", text)
if match:
print("找到花括号")
else:
print("未找到花括号")
import re
text = "This is a \\test"
match = re.search(r"\\", text)
if match:
print("找到反斜杠")
else:
print("未找到反斜杠")
注意,在正则表达式中,由于 "" 也是转义字符,所以要匹配 "" 本身,需要使用两个反斜杠 " \\ " 进行转义。