简体   繁体   English

正则表达式:使用先行断言作为条件

[英]Regexp: using lookahead assertion as condition

I believe the two regular expressions below do the same thing: 我相信下面的两个正则表达式可以做同样的事情:

\ba{3}\b

(?=\ba{3}\b).*

Both would match the second word (aaa) only: 两者都只会匹配第二个单词(aaa):

zzz aaa bbb zzz aaa bbb

I would like to know whether there's any difference between in terms of performance or any other aspect, or whether one is more advisable than the other for some reason. 我想知道在性能或其他方面是否有区别,或者出于某种原因,一个方面是否比另一个方面更可取。

EDIT: 编辑:

It's true the patterns above match different things ("aaa" and "aaa bbb"). 确实,上面的模式匹配不同的事物(“ aaa”和“ aaa bbb”)。 I'm sorry, my fault. 对不起,我的错。

My original patterns were: 我的原始模式是:

(?=^a{3}$).*
^a{3}$

and my original examples subject were: 我最初的示例主题是:

zzz
aaa
bbb

Like that I think that both patterns match "aaa". 这样,我认为这两种模式都匹配“ aaa”。

I understand that the second one is faster. 我知道第二个更快。 Is there any other difference? 还有其他区别吗?

As Jerry points out in comment, the second one matches aaa bbb . 正如杰里在评论中指出的那样,第二个匹配aaa bbb However, personally I think it'd be simpler as \\ba{3}\\b.* 但是,我个人认为\\ba{3}\\b.*会更简单\\ba{3}\\b.*

Talking about Regular Expressions, three things come to mind: 谈到正则表达式,我想到三件事:

  1. The matching domain 匹配域
  2. Complexity 复杂
  3. Speed 速度

Simplicity of any Regular Expressions to match desired strings has a direct relationship with its speed so using less expressions you'll have better speed in searching through whole text. 任何正则表达式的简单性与所需字符串的匹配都与其速度有直接关系,因此使用更少的表达式将可以更快地搜索全文。

Some expressions really cost a lot so when trying to select the best choice of your regex why should you think more?! 有些表达式的确花费很多,因此当尝试选择正则表达式的最佳选择时,为什么还要考虑更多呢?

On the regex ^a{3}$ the engine will say: I really mean it! 在正则表达式^a{3}$ ,引擎会说: 我的意思是真的! It's straight forward, simple with one obvious matching domain. 简单明了,只需一个明显的匹配域。

However in second one (?=^a{3}$).* engine doesn't mean it. 但是在第二个(?=^a{3}$).*引擎中并不是这个意思。 It has probably so many matching cases, it has a positive lookahead and consume more resources. 它可能有很多匹配的案例,前瞻性强,并且消耗更多资源。

Now, which one you're goin' to love? 现在,您要去爱哪个人?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM