Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Regex - "Not" Match

Tags:

c#

.net

regex

I have a regular expression:

12345678|[0]{8}|[1]{8}|[2]{8}|[3]{8}|[4]{8}|[5]{8}|[6]{8}|[7]{8}|[8]{8}|[9]{8}

which matches if the string contains 12345679 or 11111111 or 22222222 ... or ... 999999999.

How can I changed this to only match if NOT the above? (I am not able to just !IsMatch in the C# unfortunately)...EDIT because that is black box code to me and I am trying to set the regex in an existing config file

like image 750
David Ward Avatar asked Dec 09 '22 04:12

David Ward


2 Answers

This will match everything...

foundMatch = Regex.IsMatch(SubjectString, @"^(?:(?!123456789|(\d)\1{7}).)*$");

unless one of the "forbidden" sequences is found in the string.

Not using !isMatch as you can see.

Edit:

Adding your second constraint can be done with a lookahead assertion:

foundMatch = Regex.IsMatch(SubjectString, @"^(?=\d{9,12})(?:(?!123456789|(\d)\1{7}).)*$");
like image 51
FailedDev Avatar answered Dec 11 '22 17:12

FailedDev


Works perfectly

string s = "55555555";

Regex regx = new Regex(@"^(?:12345678|(\d)\1{7})$");

if (!regx.IsMatch(s)) {
    Console.WriteLine("It does not match!!!");
}
else {
    Console.WriteLine("it matched");
}
Console.ReadLine();

Btw. I simplified your expression a bit and added anchors

^(?:12345678|(\d)\1{7})$

The (\d)\1{7} part takes a digit \d and the \1 checks if this digit is repeated 7 more times.

Update

This regex is doing what you want

Regex regx = new Regex(@"^(?!(?:12345678|(\d)\1{7})$).*$");
like image 34
stema Avatar answered Dec 11 '22 16:12

stema