Constraint check using regular expressions

19 02 2009

I needed to check the values of a text box (with folder paths in them) to ensure they matched a constraint on the table in the database. There are a few ways you could do this, I initially thought I could check the relevant characters in the string using String.Substring() to see if they met the constraints, in this case, the first must not be a backslash and the last must be a backslash.

However I then thought it would be better to do a much more robust way, not just checking for backslashes, but also valid characters in file paths. This is how I came up with the idea to use a regular expressions. They are very useful bits of code, and definitely worth reading up on! The code I used was:

if (!Regex.IsMatch(txtMapLocation.Text, @"^[0-9a-zA-Z].*\\$"))
MessageBox.Show("Your map location must end with a backslash and there must be no backslash at the start.");

The regular expression broken down means…

^ (right at the very beginning) [0-9a-zA-Z] (there must be a number or letter, upper or lower case allowed) .*(as many letters or numbers as you wish)\\(then there must be a backslash)$(right at the end). The backslash is double slashed as backslashes are an escape character in regular expressions.