0

If i try to create regex anywhere in my code angular throws an error "Unexpected quantifier"? Why? This regex is valid, tested and works but if I try

var p = new RegExp("^(.{1,19}\*|\*.{1,19}|(?!\*).{1,20})$");

angular will throw an error. However this simple, dummy regex will not.

var pattern = new RegExp("^(.)$");

This leads me to believe that it is a matter of escaping of characters or something?

2 Answers 2

3

You need to escape the backslash in the Regex:

new RegExp("^(.{1,19}\\*|\\*.{1,19}|(?!\\*).{1,20})$");

This code will throw an exception:

new RegExp("\*.");
// SyntaxError: Invalid regular expression: /*./: Nothing to repeat

Because the string evaluates to

"*."

There is no character class before the * quantifier, so the expression is invalid.

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

Comments

1

First of all, this is a JavaScript error, not one produced by the angular framework. The regular expression you provided is invalid, as the error message states. Specifically, you need to escape backslashes in string literals. Your current expression evaluates to this:

^(.{1,19}*|*.{1,19}|(?!*).{1,20})$

What you probably want is this:

var p = new RegExp("^(.{1,19}\\*|\\*.{1,19}|(?!\\*).{1,20})$");

Resulting in the following regular expression:

^(.{1,19}\*|\*.{1,19}|(?!\*).{1,20})$

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.