Is there a function which checks the validity of a string to be used as argument to RegularExpression?

Composing regular expressions is not an easy task. In Mathematica it becomes even more difficult, since all special characters have to be escaped, i.e. \ -> \\ and so on.

I am looking for a function that will return whether a string is valid as an argument to RegularExpression, and possibly give an indication where there are syntactic, e.g. unbalanced parentheses, illegal operators and so on.

RegularExpression is very often used inside StringPosition or other functions. If I want to check the regular expression before using it, it simply evaluates itself instead of generating an error message:

RegularExpression["this is an unbalanced ("].

A regular expression validation function would only be half the battle, because the more important question of whether the regular expression serves its purpose can hardly be checked automatically. Syntactic correctness can certainly be checked automatically, and that is what I am after.

After all, such a function which I would name RegularExpressionQ[expr_String] returning True or False - especially if it prints detailed error messages in addition if there are some - could be a great work-saver!


1 Answer 1


I like this method because it is direct and fast:

RegularExpressionQ[x_String] := Quiet @ Check[
    StringMatchQ["foo", RegularExpression @ x];
  • $\begingroup$ Jason, thanks, great! Do you have any idea how to ease finding syntactical errors in a given regex? Up to now I put the regex into the expression part of regexr.com. Unfortunately even when you copy strings from Mathematica with Copy as->Plain Text you copy all those escaped double backslashes. If you use ExportString[#, "Text"]& it introduces strange characters for Umlaut-characters. If I create a shortcut using CopyToClipboard[NotebookSelection[]], I get unmotivated spaces interspersed in the result, which is fatal for regular expressions! $\endgroup$ Jan 27 at 21:35
  • $\begingroup$ My suggestion was to either evaluate the string so that it is printed to an output cell, select that cell and do the copy-as-plain-text thing or to use CopyToClipboard[string]. In my experience, that makes it so you don't copy the escaping slash and quotation marks. Do you have an example where that is adding spaces? $\endgroup$
    – Jason B.
    Jan 27 at 21:55
  • $\begingroup$ Jason: I have given an example in my more extended question mathematica.stackexchange.com/questions/279266/… $\endgroup$ Jan 29 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.