Python re.match不匹配相同的正则表达式

2024-04-20 15:43:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正面临一个奇怪的问题,我希望以前没人问过这个问题 我需要匹配两个包含“(”“)”的regexp。你知道吗

下面是我做的测试,看看为什么它不起作用:

>>> import re
>>> re.match("a","a")
<_sre.SRE_Match object at 0xb7467218>

>>> re.match(re.escape("a"),re.escape("a"))
<_sre.SRE_Match object at 0xb7467410>

>>> re.escape("a(b)")
'a\\(b\\)'

>>> re.match(re.escape("a(b)"),re.escape("a(b)"))

=>;不匹配

有人能解释为什么regexp不匹配吗?你知道吗

多谢了


Tags: importgtreobjectmatchatsreregexp
2条回答

第一个参数是pattern对象,第二个参数是匹配的实际字符串。你不应该逃避这根弦本身。记得,再逃逸转义regexp中的特殊字符。你知道吗

>>> help(re.match)
Help on function match in module re:

match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found.

>>> re.match(re.escape('a(b)'), 'a(b)')
<_sre.SRE_Match object at 0x10119ad30>

您对特殊字符进行了转义,因此正则表达式将匹配字符串"a(b)",而不是字符串
'a\(b\)',后者是re.escape('a(b)')的结果。你知道吗

相关问题 更多 >