tags:

views:

57

answers:

2

In some obscure situations a regular expression like "/^match/" works in the exact oposite way matching a line that is "something else", and the only way to fix it is to put the whole regex inside braces ... "/^(match)/", why is that happening?

+2  A: 

Just a wild guess here... the only example I can think of that would give the behaviour you describe is changing:

/^foo|bar/

to

/^(foo|bar)/

Note that the addition of parentheses changes the meaning of this regular expression. The second matches foo or bar at the beginning of the string. The first matches foo at the beginning of the string or bar anywhere in the string. This might give some false matches as you described.

It's an easy mistake to forget those parentheses... I've done it on occasion too ...blush... ;)

I can't think of any other examples right now, but I'm sure there might be other times when the addition of parentheses gives a subtle change in meaning. Next time, remember to save the example you found and post it here so we can see it.

Mark Byers
This would be my guess, too.
Alan Moore
That is exactly what happened, I did some maintenance on a cowork code and assumed that a variable with a regex was closed by braces, it wasn't ...
hack.augusto
A: 

Totally random guess, but were you using it in a split?

In javascript (I'm not as sure about PHP), if I type this:

"matchabc".split(/^match/)

I get:

["", "abc"]

Note that split uses the match to divide up the string, so you get the pieces that don't match.

However, if I do this:

"matchabc".split(/^(match)/)

I get:

["", "match", "abc"]

That's because the parentheses capture the thing I'm splitting on. This sounds a little like the behavior you're describing -- it'd be easier to tell if you post an example that illustrates the issue (not just the regex, but how you're using it and the string it's acting on).

Tim Goodman