Saturday, June 30, 2012

Regex: conditional regular expression

A few days ago I encountered a small problem in a project that I'm developing: I needed to change the regular expression for a text string so that it did not pass a string consisting of whitespaces.

To simplify the example i take this regular expression: ^[a-zA-Z0-9 ]+$ The real one was a bit more complicated, but it really does not matter. So here we have an alphanumerical string with a whitespaces.

The task was to rewrite the regular expression, so it will match the alphanumerical string with a whitespaces but not match the string containing only whitespaces. So i needed to use conditional regular expression to get over this problem.

Luckily, regular expressions allow to use if-then-else construction:

(?(condition)then|else)

If condition regular expression succeed - we use then part, otherwise - else part. By the way, the else part is optional.

So i came along to the following expression:

^(?![ ]+$)[a-zA-Z0-9 ]+$

This (?![ ]+$) condition triggers if the input string is not match the string of the whitespaces.

One more thing to remember, in javascript, when defining Regex, you should use (?(condition)then|else) expression without the (?...) framing, otherwise you get the invalid quantifier error.

No comments :

Post a Comment