Reputation: 5780
I'm working on a special regex to match a javascript regex.
For now I have this regex working:
/\/(.*)?\/([i|g|m]+)?/
For example:
'/^foo/'.match(/\/(.*)?\/([i|g|m]+)?/) => ["/^foo/", "^foo", undefined]
'/^foo/i'.match(/\/(.*)?\/([i|g|m]+)?/) => ["/^foo/i", "^foo", "i"]
Now I need to get this regex working with:
'^foo'.match(/\/(.*)?\/([i|g|m]+)?/) => ["^foo", "^foo", undefined]
Unfortunately my previous regex doesn't work for that one.
Can someone help me to find a regex matching this example (and others too):
'^foo'.match([a regex]) => ["^foo", "^foo", undefined]
Upvotes: 15
Views: 9324
Reputation: 120486
A regular expression to match a regular expression is
/\/((?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/
To break it down,
\/
matches a literal /
(?![*+?])
is necessary because /*
starts a comment, not a regular expression.[^\r\n\[/\\]
matches any non-escape sequence character and non-start of character group\[...\]
matches a character group which can contain an un-escaped /
.\\.
matches a prefix of an escape sequence+
is necessary because //
is a line comment, not a regular expression.(?:g...)?
matches any combination of non-repeating regular expression flags. So ugly.This doesn't attempt to pair parentheses, or check that repetition modifiers are not applied to themselves, but filters out most of the other ways that regular expressions fail to syntax check.
If you need one that matches just the body, just strip off everything else:
/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+/
or alternatively, add "/"
at the beginning and end of your input.
Upvotes: 26