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

前端之家收集整理的这篇文章主要介绍了正则表达式 – 原子组清晰度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑这个正则表达式.
a*b
@H_502_3@在aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac的情况下,这将失败

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

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

(?>a*)b
@H_502_3@在aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac的情况下,这将失败

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

@H_502_3@最后这个正则表达式:

a*+b  (a variant of atomic group)
@H_502_3@在aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac的情况下,这将失败

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

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

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

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

@H_502_3@他们的工作方式不同吗

@H_502_3@Author note:

@H_502_3@ 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!

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

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

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

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

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

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

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

@H_502_3@也许相关:

@H_502_3@> Why is a character class faster than alternation?

猜你在找的正则表达式相关文章