0

In python you can compile multiple regexes with labels into a single regex. The user can apply one regex and it returns the label along with other information (and should be more efficient than applying each regex separately). Is there an equivalent capability in javascript or node.js? Provide an example please.

As an example case. You have a regex for phone numbers, one for dates and one for IP addresses. The 3 regexes are compiled into one with associated labels (phone number, date, IP address). When the regex is applied, it returns the label along with other standard regex information.

Thanks

user3071643
  • 1,405
  • 1
  • 15
  • 18
  • 1
    Test each regex independently. The one that matches is the one that matches? You can create an array of regex patterns and loop over it. – ctwheels Feb 08 '18 at 18:47
  • 1
    Possible duplicate of [How can I access the expression that caused a match in a conditional match group Javascript regex?](https://stackoverflow.com/questions/48667341/how-can-i-access-the-expression-that-caused-a-match-in-a-conditional-match-group) – ctwheels Feb 08 '18 at 18:48
  • You can get a more efficient solution by "compiling" all regexs together so they are part of the same tree - so that's why you want to combine them as opposed to loop over them and do an individual comparison against each (see xregexp as described below for how to do it). – user3071643 Feb 09 '18 at 15:25

1 Answers1

0

Ok, so what I was looking for is called a regex "named capture group", and it was answered in this question Named capturing groups in JavaScript regex?

In short, you need to use the package xregexp. Here is an example of using xregexp named capture groups (as taken from the referenced page)

date = XRegExp(`(?<year>  [0-9]{4} ) -?  # year
            (?<month> [0-9]{2} ) -?      # month
            (?<day>   [0-9]{2} )         # day`, 'x');
user3071643
  • 1,405
  • 1
  • 15
  • 18