views:

74

answers:

3

Can you guys help me figure this out? I have the following JavaScript snippet:

pattern = new RegExp('^bla*a', 'i');
console.debug(pattern.exec('blatr'));

After I run this, the output is ["bla"]. The way I interpret this regular expression is this: find me a string that starts with 'bla' and ends with 'a', with as many characters in between. In this case, 'blatr' shouldn't match the regular expression but it does. What am I doing wrong?

Thanks.

A: 

The a* in your expression is matching the preceding character a zero or more times, not the string bla. You'll need to use parentheses. Try this:

new RegExp('(^bla){1}.+a$', 'i');

EDIT: No point in using + in an expression that matches the beginning of a string. Also, since you say you want to match any characters in between bla and a you'll need to use a + after the .

EDIT: Ahem, seems one doesn't need parentheses either as the other answers show. Note to self: Stop over-engineering your RegEx's and test your answers before you post them. :P This is fine:

new RegExp('^bla.+a$', 'i');
brownstone
+4  A: 

A '*' signifies {0,} or "0 or more" of the preceding character. What you're trying to do should be

^bla.*a$

edit: missed the "ends with 'a'" part of the question earlier.

aditya
Just append $ to end of this regex, otherwise it match "blatraddd" also.
Kamarey
Missed that part in the question. Corrected :)
aditya
A: 

Your regex matches the letters bl at the beginning of the line followed by zero or more a's and then one a (which is equivalent to one or more a's) with possibly characters following that. blatr matches that.

To do what you want to do (if I understand correctly, use:

'^bla.*a'

The * means repeat the previous character zero or more times

Peter van der Heijden