skeggse skeggse - 1 year ago 146
Javascript Question

Javascript greedy regex appears non-greedy

I'd like to match a three-part string. The first part consists of one or more

characters, the second part consists of one or more
characters, and the third part consists either of zero or more
characters or zero or more
characters, but not a mix of

As such, I wrote the following regular expression:


And immediately noticed that it fails to greedily match the trailing
s in the following string:


Wrapping the inner clauses of the or clause does not fix the unexpected behavior:


But interestingly both regular expressions match the following, where the
characters match the first clause of the or:


The following regular expression captures the semantics accurately, but I'd like to understand why the original regular expression behaves unexpectedly.


Answer Source

I think you want


That is, if it finds a C it will match as many more C as possible, if it finds a c it will match as many more c as possible. But finding C or c is optional.

Your regex doesn't work because first it tries C*, which matches the empty string, which is OK. Then it won't try to check if c* can match more characters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download