简体   繁体   English

正则表达式匹配 C# 中除二进制数以外的任何内容?

[英]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.我想检查字符串是否只包含0s1s ,没有别的。 If it includes anything else apart from 0 and 1 , I want to catch it.如果它包含除01之外的任何其他内容,我想抓住它。 Even if single character is something different than 0 or 1 .即使单个字符与01不同。

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?有任何想法吗?

尝试这个

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

Rather than that try to inverse it.而不是尝试反转它。

Check if binaryNumber does NOT match Regex for binary numbers only.检查 binaryNumber 是否仅与二进制数的 Regex 不匹配。

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
}

Try尝试

^[01]*$

Accepts any number of digits, including none.接受任意数量的数字,包括无。

or或者

^[01]+$

Accepts one or more digits.接受一位或多位数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM