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.
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:
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. 😛 This is fine: