typos
typos

Reputation: 6632

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?

Upvotes: 3

Views: 1240

Answers (4)

Mostafiz
Mostafiz

Reputation: 7352

Try this

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

Upvotes: 3

MarcM
MarcM

Reputation: 2251

Try

^[01]*$

Accepts any number of digits, including none.

or

^[01]+$

Accepts one or more digits.

Upvotes: 0

Pawel Troka
Pawel Troka

Reputation: 853

Rather than that try to inverse it.

Check if binaryNumber does NOT match Regex for binary numbers only.

private static int bin(string binaryNumber) {

  Regex rgx = new Regex(@"^[01]+$");
  if (!rgx.IsMatch(binaryNumber)) {
    Console.WriteLine("Binary number should include only 0 and 1");
  }

  // rest removed for brevity
}

Upvotes: 1

Vivek Nuna
Vivek Nuna

Reputation: 1

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

Upvotes: 1

Related Questions