Reputation: 6632
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
Reputation: 2251
Try
^[01]*$
Accepts any number of digits, including none.
or
^[01]+$
Accepts one or more digits.
Upvotes: 0
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