Javascript re-expression to match regex

I am working on a special regex to match the javascript regex.

Now I have this regex:

/\/(.*)?\/([i|g|m]+)?/ 

For instance:

 '/^foo/'.match(/\/(.*)?\/([i|g|m]+)?/) => ["/^foo/", "^foo", undefined] '/^foo/i'.match(/\/(.*)?\/([i|g|m]+)?/) => ["/^foo/i", "^foo", "i"] 

Now I need to get this regular expression to work with:

 '^foo'.match(/\/(.*)?\/([i|g|m]+)?/) => ["^foo", "^foo", undefined] 

Unfortunately, my previous regex does not work for this.

Can someone help me find a regex matching this example (and others too):

 '^foo'.match([a regex]) => ["^foo", "^foo", undefined] 
+4
source share
1 answer

Regular expression to match regular expression

 /\/((?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/ 

To smash it,

  • \/ matches literal /
  • (?![*+?]) necessary because /* starts a comment, not a regular expression.
  • [^\r\n\[/\\] matches any character in a non-escape sequence and a non-start character group
  • \[...\] matches a character group that may contain un-escaped / .
  • \\. matches the escape sequence prefix
  • + necessary because // is a line comment, not a regular expression.
  • (?:g...)? matches any combination of non-repeating regular expression flags. So ugly.

It does not try to join parentheses or verify that repetition modifiers do not apply to themselves, but filter out most of the other ways in which regular expressions cannot check syntax.

If you need one that matches only the body, just undo everything else:

 /(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+/ 

or, conversely, add "/" to the beginning and end of your input.

+6
source

Source: https://habr.com/ru/post/1493290/


All Articles