Search code examples
c#regexstringalphanumeric

Regex conditional not returning false on the minimum underscores


I am using this RegEx in if RegEx is match

 if (Regex.IsMatch(_familyname, @"(\S*_){3}\S"))

I tried to ensure that the word passing the test had at least this Word1_Word2_WORD3-maybe_Word4 (note hyphens or spaces within are word are not important) The RegEx (\S*_){3}\S allows a word with two underscores to pass also. Is there a RegEx match for only three underscores and any word/character/symbol is allowed between these underscores? Oh also it never ends or starts with an underscore either. Also if a test that the third alphanumeric string was all capitals would be great. Actually I achieved all this using string split. However I read RegEx can be faster? Also using .NET 4.5.2


Solution

  • I had to add another regex conditional to prevent users creating a name with 4 underscores, this prevents the most common error, they might add more so it's not the most elegant solution, besides it might run slower than a solution that uses one regex statement. Thanx Mageos for the greedy, lazy and possessive tutorial, I used + to get less matches using regex storm so I am guessing that this is a quicker method than I had before.

    Regex.IsMatch( familyname, @"(\S+){3}\S")
    &! Regex.IsMatch(familyname, @"(\S+){4}\S")