Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for numbers only

Tags:

c#

regex

I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions.

string compare = "1234=4321"; Regex regex = new Regex(@"[\d]");  if (regex.IsMatch(compare)) {      //true }  regex = new Regex("[0-9]");  if (regex.IsMatch(compare)) {      //true } 

In case it matters, I'm using C# and .NET2.0.

like image 553
Timothy Carter Avatar asked Nov 07 '08 18:11

Timothy Carter


People also ask

What is the regex for only numbers?

The \d can be used to match single number. Alternatively the [0-9] can be used to match single number in a regular expression. The [0-9] means between 0 and 9 a single number can match.

Can regex be used for numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

How do you match a number in regex?

\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

How do you check if a string contains only numbers in JS?

To check if a string contains only digits, use the test() method with the following regular expression /^[0-9]+$/ . The test method will return true if the string contains only digits and false otherwise.


2 Answers

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$"); 

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

like image 169
Bill the Lizard Avatar answered Sep 30 '22 13:09

Bill the Lizard


Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:

regex = new Regex("^[0-9]+$"); 

The ^ will anchor the beginning of the string, the $ will anchor the end of the string, and the + will match one or more of what precedes it (a number in this case).

like image 35
Robert Gamble Avatar answered Sep 30 '22 12:09

Robert Gamble