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

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!

RegularExpressionQ[x_String] := Quiet @ Check[

• 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! Jan 27 at 21:35
• 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? Jan 27 at 21:55