Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Regex for numbers and dash only

Tags:

I have the following in my c# code - what I like it to do is to check to see if the expression has numbers or a dash but nothing else. If I type in the letter K along with a dash or number it still accepts it. How do I say just have the express be numbers or a dash:

     Match match = Regex.Match(input, @"[0-9-]");

Note that input is the text that I am passing for evalution.

like image 475
Nate Pet Avatar asked Jan 06 '12 16:01

Nate Pet


2 Answers

Match match = Regex.Match(input, @"^[0-9-]*$");

The ^ means that the match should start at the beginning of the input, the $ that it should end at the end of the input.

The * means that (only) 0 or more numbers or dashes should be there (use + instead for 1 or more).

like image 179
Hans Kesting Avatar answered Sep 30 '22 00:09

Hans Kesting


Your Regex matches that any digit or dash exists within the string, try the following:

Regex.Match(input, @"^[\d-]+$");

^ Start of string

[\d-]+ one or more digits or dashes

$ End of string

like image 42
mynameiscoffey Avatar answered Sep 30 '22 00:09

mynameiscoffey