I am using regex to check if the string contains only numbers, dashes and spaces:
Regex regex = new Regex(@"^[0-9- ]+$");
if(!regex.IsMatch(str))
How can I do this without regex?
I am using regex to check if the string contains only numbers, dashes and spaces:
Regex regex = new Regex(@"^[0-9- ]+$");
if(!regex.IsMatch(str))
How can I do this without regex?
You can use linq to iterate over the characters, and char.IsDigit
to check for a digit.
bool invalid = myString.Any( x => x != ' ' && x != '-' && !char.IsDigit(x) );
Here's a LINQ solution:
var allowedChars = "1234567890- ";
var str = "3275-235 23-325";
if (str.All(x => allowedChars.Contains(x))){
Console.WriteLine("true");
}