为什么这个正则表达式不匹配带有百分比符号的字符串?

Why isn't this regex matching a string with percentage symbol?

我有一个包含以下输入的文件:

xa%1bc
ba%1bc
.
.

等等。我想使用 matchregex 来识别其中包含 a%1b 的行。 我正在使用

 import re
 p1 = re.compile(r'\ba%1b\b', flags=re.I)
 if re.match(p1,linefromfile):
    continue

它似乎没有检测到带有 %1 的行。问题是什么?谢谢

你可以试试

if 'a%1b' in linefromfile:

如果你需要正则表达式

if re.match('a%1b', linefromfile):

match 只搜索字符串开头的模式,如果要查找字符串是否包含模式,请改用 search。此外你不需要边界这个词,\b:

re.search(pattern, string, flags=0)

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

import re
if re.search(r"a%1b", "xa%1bc"):
    print("hello")
# hello