0

In JS, is there a regex to check the given regex itself is valid or not?

Santhosh V
  • 380
  • 1
  • 11
  • 2
    With that said, just...compile the regex. – VLAZ Jan 30 '19 at 14:03
  • 1
    If a regular expression is syntactically incorrect, you'll get an error from the parser or from the RegExp constructor. – Pointy Jan 30 '19 at 14:03
  • 3
    why not just use ```try..catch``` – Danyal Imran Jan 30 '19 at 14:04
  • @vlaz I too tried this answer, but it seems not valid for javascript. – Santhosh V Jan 30 '19 at 14:05
  • 1
    I actually recommend starting off with a tool like [regex101](http://www.regex101.com), which can be a nice sandbox in which to test things. – Tim Biegeleisen Jan 30 '19 at 14:05
  • 1
    @vlaz Your link to duplicate question leads to general `regex` question, but not to `javascript` one. – cn007b Jan 30 '19 at 14:12
  • @VladimirKovpak the second most voted answer is still relevant - just try to initiate a regex and see if there is a problem. The most voted (and accepted) answer is a very good demonstration of *why you don't want to validate regex with regex*. It's too complex and very hard to maintain. The fact that it doesn't work in JS by copy/pasting is nothing more than a very practical example of that. You can change it, if you want - there are suggestions for how in that same answer. And maybe you have enough regex grammar in JS to have a regex for validating regexes but, again do you want to? – VLAZ Jan 30 '19 at 14:18
  • @VladimirKovpak and I actually see now that your very own answer is not much different from the second answer in the dupe. You are using `try...catch` exactly as advised there. – VLAZ Jan 30 '19 at 14:20
  • 1
    @vlaz Yes, true. And I like accepted answer from your link! But my worries related to fact that OP may be perplexed why js related question duplicates with non-js related question... – cn007b Jan 30 '19 at 14:30

1 Answers1

4

You can wrap you code into try-catch block, like this:

try {
  re = new RegExp(/(.*/); // or re = /(.*/;
} catch (err) {
  console.log("ERR:", err);
}

Result:

ERR: SyntaxError: Invalid regular expression: /(.*/: Unterminated group
cn007b
  • 16,596
  • 7
  • 59
  • 74
  • 1
    Your `new RegExp` is a bit pointless, unless you are going to pass a string instead. just doing `re = /(.*/;` would have done the same. – Keith Jan 30 '19 at 14:12
  • 1
    @Keith Yep, completely agree! But I decide to use this one because it feels like regex must be provided from outside world. – cn007b Jan 30 '19 at 14:14