views:

34

answers:

2

I apologize in advance for what is probably a simply question, but I suck at regular expressions and I did not find my answer via Google...

My Question is as follows:

Using ASP.NET syntax for the RegularExpressionValidator control, how do you specify restriction of two consecutive characters, say character 'x'?

Thanks in advance...

A: 

You can provide a regex like the following:

(\\w)\\1+

(\\w) will match any word character, and \\1+ will match whatever character was matched with (\\w).

I do not have access to asp.net at the moment, but take this console app as an example:

Console.WriteLine(regex.IsMatch("hello") ? "Not valid" : "Valid"); // Hello contains to consecutive l:s, hence not valid

Console.WriteLine(regex.IsMatch("Bar") ? "Not valid" : "Valid"); // Bar does not contain any consecutive characters, so it's valid
alexn
I don't understand this answer. I tried a RegularExpressionValidator with ValidationExpression="^([^x])\\1+$" and it did not work.
harrije
A: 

Alexn is right, this is the way you match consecutive characters with a regex, i.e. (a)\1 matches aa.

However, I think this is a case of everything looking like a nail when you're holding a hammer. I would not use regex to validate this input. Rather, I suggest validating this in code (just looping through the string, comparing str[i] and str[i-1], checking for this condition).

steinar
OK, I know what to do in the code behind... It's now a mental challenge to figure out what to do with the ASP.NET RegularExpressionValidator control. I still don't know what to assign to ValidationExpression. I tried ValidationExpression="^([^(x)]\1)$" and various other variations and I still don't have an RE that works to eliminate input with two consecutive values of 'x'.
harrije
I see. In my mind it's not worth the mental challenge (from a practical standpoint), as I believe regexes are not really meant to solve exactly this problem.
steinar