Regular expressions are a powerful tool for validating inputs, but what if your input is itself a regular expression? Is there a regular expression that can validate regular expressions?

Well, yes, if your regular expression engine supports recursion: /^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/.

Today’s Representative Line (which is more than a single line) comes from Ryan S, who found an implementation of isValidRegex which is perhaps a bit more elegant:

	public static bool isValidRegEx(string value)
            // intent is to block empty strings from being accepted
            return !string.IsNullOrEmpty(value);

You might be thinking, “That doesn’t validate anything at all!”, but at least it doesn’t summon dread Cthulhu from R’gexyleh. I count that as a win.

[Advertisement] Release! is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!