-1

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
appy243
  • 1
  • 3
  • You can use `String.Contains` to check for a character, and [this page](https://stackoverflow.com/questions/18251875/in-c-how-to-check-whether-a-string-contains-an-integer) shows how to check for a digit. – The fourth bird Aug 17 '21 at 20:55
  • 5
    Seems like a perfectly reasonable use of a RegEx. Why make things harder and slower? – Joel Coehoorn Aug 17 '21 at 21:04

2 Answers2

0

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) );
John Wu
  • 50,556
  • 8
  • 44
  • 80
0

Here's a LINQ solution:

var allowedChars = "1234567890- ";
var str = "3275-235 23-325";

if (str.All(x => allowedChars.Contains(x))){
    Console.WriteLine("true");
}
lrpe
  • 730
  • 1
  • 5
  • 13