Skip to content

Instantly share code, notes, and snippets.

@vitaly-t
Created January 6, 2021 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitaly-t/05d6c8882a93e9303480d58e3cb12f77 to your computer and use it in GitHub Desktop.
Save vitaly-t/05d6c8882a93e9303480d58e3cb12f77 to your computer and use it in GitHub Desktop.

Is there a regular expression to detect a valid regular expression?.

Deleted from StackOverflow by the author, because oddly, it got many downvotes.


Reflecting on this in 2016, in the way that things changed since...

The direct answer to the question is still the resounding NO, it is impossible to implement a regular expression to find all regular expressions in your code.

A regular expression can only be used to find most of regular expressions, but never all of them, due to the syntax complexity that regular expressions support.

There are cases where the only way to detect a regular expression is via a full-expression analysis.

Here's just one such complex case for you:

func(a / 2, /regex/, b / 3);

Even to write an algorithm that could detect for certain where a regular expression is in such a case is a very challenging task.

As I mentioned above, it requires a full-expression anaysis, which in turn requires that you first tokenize all your code. Luckily, today this set of tasks is implemented by every AST parser.

See AST Explorer for a good list of them.

The only right way to locate all regular expressions correctly is through one of AST parsers, which today exist in a wide variety.

The following question can help you get started: Enumerate regular expressions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment