0

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.

1
  • Any reason why my answer wasn't picked? (I want to know purely for personal academic analysis, of course). Commented Sep 7, 2009 at 10:24

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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');

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.