Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

python - 正则表达式与python中的预期输出不匹配[重复](Regex does not match expected output in python [duplicate])

While writing a program to detect repeating patterns in binary I came across a weird instance where a regex does not seem to properly match in python. (在编写程序以检测二进制中的重复模式时,我遇到了一个奇怪的实例,其中regex在python中似乎不正确匹配。)

The regex is ran as followed: (正则表达式如下运行:)

pattern = re.compile("^0b(1*)(0*)(12)*(1)?$")
result = pattern.match("0b101")

What I would expect to see is the following matching groups: (我希望看到以下匹配组:)

  • 1: '1' (1:'1')
  • 2: '0' (2:“ 0”)
  • 3: empty (3:空)
  • 4: '1' (4:“ 1”)

But instead I get no match at all. (但是相反,我根本没有比赛。) According to the website regex101 the match should be as expected, but python seems to disagree. (根据网站regex101的描述,匹配应该与预期的一样,但是python似乎不同意。)

Is there a difference between interpreters in python and the website or just some small mistake I'm missing? (python和网站中的解释器之间有区别还是只是我遗漏了一些小错误?)

  ask by martijn p translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

and the website (和网站)

I'm assuming you created your regex using one of the websites like regex101, right? (我假设您使用像regex101这样的网站之一创建了regex,对吗?)

If you look closely, regex101, it hints it uses raw strings. (如果仔细观察一下regex101,它暗示它使用的是原始字符串。)

In your case: (在您的情况下:)

pattern = re.compile("^0b(1*)(0*)(12)*(1)?$")

Python tries to interpret \1 as normal escape sequences - like \n etc. (Python尝试将\1解释为正常的转义序列-如\n等。)

What you need, is \ that after string parsing, regex parser can parse. (您需要的是\ ,在字符串解析后,正则表达式解析器可以解析。)

This means, escaping the backslash - \\ or using a raw string, so that Python knows it shouldn't parse any \n s and similar ones. (这意味着,转义反斜杠- \\或使用原始字符串,以便Python知道它不应解析任何\n和类似的\n 。)

pattern = re.compile(r"^0b(1*)(0*)(12)*(1)?$")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...