0

I have a regular expression and I want to check this regular expression is valid or not(correct format).

I try to use this code as below to check but it run not good

var regExp = new RegExp();
regExp.compile("^[\d\-]{0,64}"); => check OK.
regExp.compile("[[\d\-]{0,64}"); => check Not Good.

How to check my regular expression is correct format or not? Please help me handle this case.

4
  • 1
    Need to escape the second [ to match it literally Commented Nov 11, 2015 at 4:28
  • 1
    Are you asking for a way to check if your JavaScript syntax be correct, or do you want a way to check if the regex be logically correct (meaning it matches what you want to match) ? Commented Nov 11, 2015 at 4:28
  • Use try/catch around the regexp definition. Commented Nov 11, 2015 at 4:30
  • Seems slightly odd to mark a question as a duplicate of a question which was closed. Commented Nov 14, 2015 at 7:10

1 Answer 1

1

Use try/catch to catch the error when creating the regexp.

Object.defineProperty(RegExp, 'compile', {
    value: function (regexp) {
        try {
            new RegExp(regexp);
            return "OK";
        } catch(e) {
            return "Not Good";
        }
    }
});

Some might object to adding methods to the RegExp object. In the above, I've adopted your proposed interface implementing this as RegExp.compile.

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

4 Comments

Quick Q: Why not defining property directly on RegExp proto? Any advantage of using Object.def...
new RegExp("[[\d-]{0,64}") return error ?
@guest271314 This will not return error. This will only check if the passed string can be complied to regex. And for your example, the regex is compiled to /[[d-]{0,64}/ which is valid regex, but will not match what OP/you might expect.
@Tushar There is no way to check if a regexp does what the OP expects, because the computer has no way to know what he expects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.