David Ward
David Ward

Reputation: 3829

.NET Regex - "Not" Match

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

Upvotes: 4

Views: 16681

Answers (4)

Justin Morgan
Justin Morgan

Reputation: 30700

First of all, you don't need any of those [] brackets; you can just do 0{8}|1{8}| etc.

Now for your problem. Try using a negative lookahead:

@"^(?:(?!123456789|(\d)\1{7}).)*$"

That should take care of your issue without using !IsMatch.

Upvotes: 2

FailedDev
FailedDev

Reputation: 26940

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}).)*$");

Upvotes: 10

stema
stema

Reputation: 93036

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})$).*$");

Upvotes: 2

ean5533
ean5533

Reputation: 8994

I am not able to just !IsMatch in the C# unfortunately.

Why not? What's wrong with the following solution?

bool notMatch = !Regex.Match(yourString, "^(12345678|[0]{8}|[1]{8}|[2]{8}|[3]{8}|[4]{8}|[5]{8}|[6]{8}|[7]{8}|[8]{8}|[9]{8})$");

That will match any string that contains more than just 12345678, 11111111, ..., 99999999

Upvotes: 0

Related Questions