typos typos - 1 month ago 5
C# Question

Regular expression to match anything except binary numbers in C#?

I want to check whether the string includes only

0s
and
1s
, and nothing else. If it includes anything else apart from
0
and
1
, I want to catch it. Even if single character is something different than
0
or
1
.

I wrote the following regular expression, but it doesn't seem to catch anything.

private static int bin(string binaryNumber) {

Regex rgx = new Regex(@"^[a-zA-Z2-9\p{P}\p{S}\s,]*$");
if (rgx.IsMatch(binaryNumber)) {
Console.WriteLine("Binary number should include only 0 and 1");
}

// rest removed for brevity
}


Any ideas?

Answer

Try this

Regex rgx = new Regex(@"[^01]+$");