Question

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:

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"). 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".

I understand that the second one is faster. Is there any other difference?

Was it helpful?

Solution 2

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! It's straight forward, simple with one obvious matching domain.

However in second one (?=^a{3}$).* engine doesn't mean it. It has probably so many matching cases, it has a positive lookahead and consume more resources.

Now, which one you're goin' to love?

OTHER TIPS

As Jerry points out in comment, the second one matches aaa bbb. However, personally I think it'd be simpler as \ba{3}\b.*

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top