微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 原子组清晰度

考虑这个正则表达式.
a*b

在aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac的情况下,这将失败

这需要调试器中的67个步骤才能失败.

现在考虑这个正则表达式.

(?>a*)b

在aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac的情况下,这将失败

这需要在调试器中执行133步才能失败.

最后这个正则表达式:

a*+b  (a variant of atomic group)

在aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac的情况下,这将失败

这需要调试器中的67个步骤才能失败.

当我检查基准原子组(?> a *)时,b的执行速度提高了179%.

现在原子组禁用回溯.所以比赛中的表现很好.

>但为什么步数更多?有人可以解释一下吗?
>为什么会有差异.在两个原子团(?> a *)b和a * b之间的步骤中.

他们的工作方式不同吗

Author note:

This answer targets question 1 as delivered by the bounty text “I am looking forward to the exact reason why more steps are being needed by the debugger.I dont need answers explaining how atomic groups work.”;
07000 addresses the other concerns very well,while 07001 takes a ride through the mentioned constructs,how they work,and why they are important. For full kNowledge,simply reading this post is not enough!

正则表达式中的每个组都需要一步进入和退出组.

什么?!
是的,我很认真,继续读下去……

首先,我想向你展示量化的非捕获组,而没有组:

Pattern 1: (?:c)at
Pattern 2: cat

那么到底发生了什么?我们将模式与正则表达式引擎上的测试字符串“concat”匹配,并禁用优化:

在我们参加的同时,我会向您介绍更多的团体:

不好了!我要避免使用群组!

可是等等!请注意,匹配所需的步骤数与匹配的性能无关.正如我所提到的,pcre引擎优化了大部分“不必要的步骤”.尽管在禁用优化的引擎上采取了更多步骤,但原子组仍然是最有效的.

也许相关:

> Why is a character class faster than alternation?

原文地址:https://www.jb51.cc/regex/357273.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐