I m trying to matching a string which will not allow same special character at same time
my regular expression is:
[RegularExpression(@"^ [a-zA-Z0-9] [a-zA-Z0-9.&' '-] [a-zA-Z0-9]$")]
this solve my all requirement except the below two issues
this is my string : bracks
acceptable :
bra-cks, b-r-a-c-ks, b.r.a.c.ks, bra cks (by the way above regular expression solved this)
not acceptable:
issue 1: b.. or bra..cks, b..racks, bra...cks (two or more any special character together),
issue 2: bra cks (two ore more white space together)
CodePudding user response:
To match a string using a regular expression that does not allow the same special character to appear more than once at a time, you can use a negative lookahead assertion. A negative lookahead assertion is a pattern that matches a string only if it is not followed by a certain pattern.
^(?!.*(.)\1)[^A-Za-z0-9]*$
CodePudding user response:
I don`t know why you need to use regex, but you can try to check if there are two special chars in a row using Linq.
Example with two dots in a row.
string s = "s.t.r.i..n.g";
bool hasTwoDotsInARow = s.ToCharArray()
.Select((c, i) => new { c, i })
.Any(x => x.c == '.' && x.i > 0 && s[x.i - 1] == '.');
Console.WriteLine(hasTwoDotsInARow);