348

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.

Nicolás Alarcón Rapela
  • 1,998
  • 1
  • 13
  • 27
Timothy Carter
  • 14,238
  • 7
  • 40
  • 62
  • 3
    Why not TryParse the string for that simple case? bool decimal.TryParse(string string, out decimal result) or bool int.TryParse(string string, out int result) – Makach Nov 03 '10 at 09:55
  • Try.Parse will accept a plus or minus sign at the start, and leading/trailing spaces. – Robin Bennett Jan 24 '11 at 10:40
  • 6
    Do you need to match _numbers_ or _digits_? For example: 123.456 is a number, but it's not all digits. – Joel Coehoorn Nov 07 '08 at 18:54
  • Exactly, OP is not totally clear about using integers or not – Sune Rievers Dec 12 '09 at 23:26
  • 1
    Look at [this answer](http://stackoverflow.com/questions/4246077/simple-problem-with-regular-expression-only-digits-and-commas/4247184#4247184) for a definitive treatment of parsing numbers with regular expressions. – tchrist Nov 23 '10 at 14:53
  • 1
    In general, the easiest way to troubleshoot Regex expressions, in my opinion, is by using a command line interpreter, if your language allows it (seems that most do). Since this example is in C#, you can use http://www.linqpad.net/, or you could use a breakpoint in the debugger and then use the Immediate window in VS as a CLI. – andrew Feb 18 '15 at 19:18

18 Answers18

544

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.

Community
  • 1
  • 1
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
  • How about a set number of numeric values? This is usually so for postal codes of certain countries like India. I guess we may have to do a string length check after this? – Najeeb Mar 13 '18 at 10:59
  • 2
    @Najeeb Yes, since Indian zip codes are 6-digit numbers, you can use something like `"^\d{6}$"`. Some other countries have more complicated rules for zip codes, so regex solutions for multiple countries can get pretty complicated too. Check out some of the examples at https://stackoverflow.com/q/578406/1288 – Bill the Lizard Mar 13 '18 at 12:15
  • How come if the input string is something like: "3 a" it will still match? Does anyone know how I can get it to match ONLY if there are numbers, and nothing else (except for a negative sign I suppose). I currently have it set up like this "-?[0-9]+". – Matthew Dec 22 '18 at 22:45
119

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).

Taz
  • 3,527
  • 2
  • 33
  • 54
Robert Gamble
  • 97,930
  • 23
  • 141
  • 137
46

If you need to tolerate decimal point and thousand marker

var regex = new Regex(@"^-?[0-9][0-9,\.]+$");

You will need a "-", if the number can go negative.

Community
  • 1
  • 1
Andy
  • 5,266
  • 2
  • 37
  • 28
  • @Florin Ghita. Thanks. "-" needs to be at the beginning. – Andy Mar 19 '13 at 22:38
  • 3
    This regex also wrongly permits the leading negative sign (`-`) and period (`.`) to occur more than once. – DavidRR Apr 09 '14 at 14:36
  • 5
    you can make `-` and `.` optional via `?`. `-?\d+(?:\.\d+)?` would match integers or decimals. (The `?:` in the parens just makes the parens a non-capturing group and used to only group for clarity.) – butterywombat Sep 29 '14 at 16:10
  • 2
    It fails for edge cases like 1,.5 , but if you oversee that. still it fails for basic cases like -2. Please alter it to `^-?[0-9][0-9,\.]*$` to avoid failing for the basic case. + is replaced with * – PrivateOmega Jan 12 '19 at 09:30
  • One scenario I am missing here is the Engineering notation (1.2345e-4) any suggestion about that? – WolfiG Jun 13 '19 at 08:53
  • doesn't matches "0" – Sadiq Khoja Mar 25 '20 at 17:40
20

This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator ,

"^-?\\d*(\\.\\d+)?$"

some strings that matches with this:

894
923.21
76876876
.32
-894
-923.21
-76876876
-.32

some strings that doesn't:

hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.
Daniele D.
  • 2,416
  • 3
  • 34
  • 42
ultraklon
  • 550
  • 4
  • 9
19

It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.

^\d+$
kasperjj
  • 3,478
  • 24
  • 23
18

Perhaps my method will help you.

    public static bool IsNumber(string s)
    {
        return s.All(char.IsDigit);
    }
Raz Megrelidze
  • 2,443
  • 1
  • 22
  • 26
  • 3
    Keep in mind though that [`Char.IsDigit`](http://msdn.microsoft.com/en-us/library/0t641e58%28v=vs.110%29.aspx) returns `true` for any character that is a member of the [UnicodeCategory.DecimalDigitNumber](http://msdn.microsoft.com/en-us/library/system.globalization.unicodecategory(v=vs.110).aspx) category. This may not be what the OP wants. Also see [Why Char.IsDigit returns true for chars which can't be parsed to int?](http://stackoverflow.com/q/22063436/1497596). – DavidRR Apr 09 '14 at 15:05
  • See [Unicode Characters in the 'Number, Decimal Digit' Category](http://www.fileformat.info/info/unicode/category/Nd/list.htm). – DavidRR Apr 09 '14 at 15:08
12

Sorry for ugly formatting. For any number of digits:

[0-9]*

For one or more digit:

[0-9]+
fnc12
  • 2,113
  • 1
  • 18
  • 25
11

If you need to check if all the digits are number (0-9) or not,

^[0-9]+$

1425 TRUE

0142 TRUE

0 TRUE

1 TRUE

154a25 FALSE

1234=3254 FALSE

11

^\d+$, which is "start of string", "1 or more digits", "end of string" in English.

Mark Brackett
  • 81,638
  • 17
  • 102
  • 150
11

Here is my working one:

^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$

And some tests

Positive tests:

string []goodNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};

Negative tests:

string []badNums={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};

Checked not only for C#, but also with Java, Javascript and PHP

Marina
  • 754
  • 13
  • 19
  • ".3","3." are actually good numbers (meaning 0.3 and 3.0 respectively). we see this all the time in source systems, and most to_number(xx) functions of the languages you have mentioned will recognize and conver them correctly. thanks. – Tagar Feb 22 '16 at 05:31
  • 1
    @Ruslan you are right that in many systems ".3","3." would parse to valid number and used as you mentioned "0.3" and "3.0". But in the other hand - that is _converted_ value, so _original_ value ".3" and "3." isn't really existing number. – Marina Feb 22 '16 at 20:17
7

While non of the above solutions was fitting my purpose, this worked for me.

var pattern = @"^(-?[1-9]+\d*([.]\d+)?)$|^(-?0[.]\d*[1-9]+)$|^0$|^0.0$";
return Regex.Match(value, pattern, RegexOptions.IgnoreCase).Success;

Example of valid values: "3", "-3", "0", "0.0", "1.0", "0.7", "690.7", "0.0001", "-555", "945465464654"

Example of not valid values: "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "--1", "-.1", "-0", "00099", "099"

Daniele D.
  • 2,416
  • 3
  • 34
  • 42
5

Another way: If you like to match international numbers such as Persian or Arabic, so you can use following expression:

Regex = new Regex(@"^[\p{N}]+$");

To match literal period character use:

Regex = new Regex(@"^[\p{N}\.]+$");
S.M.Mousavi
  • 4,279
  • 6
  • 37
  • 50
5

Regex for integer and floating point numbers:

^[+-]?\d*\.\d+$|^[+-]?\d+(\.\d*)?$

A number can start with a period (without leading digits(s)), and a number can end with a period (without trailing digits(s)). Above regex will recognize both as correct numbers.

A . (period) itself without any digits is not a correct number. That's why we need two regex parts there (separated with a "|").

Hope this helps.

Tagar
  • 10,563
  • 4
  • 78
  • 99
5

Use beginning and end anchors.

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

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

Oli Folkerd
  • 5,658
  • 1
  • 19
  • 35
3

I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12 Also this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22 In addition to this numbers like .55 or ,55 would pass. This may be handy.

^([,|.]?[0-9])+$
Azur
  • 53
  • 4
2

If you want to extract only numbers from a string the pattern "\d+" should help.

James Selvakumar
  • 2,317
  • 1
  • 18
  • 27
1
 console.log(/^(0|[1-9][0-9]*)$/.test(3000)) // true
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. [How to Answer](https://stackoverflow.com/help/how-to-answer) – Elletlar Nov 12 '20 at 10:14
-4

Regex regex = new Regex ("^[0-9]{1,4}=[0-9]{1,4]$")

  • 5
    Can you explain your answer a bit please? You'll notice that the other answers to this question have some level of explanation of what each part of the regex does, which you are lacking. – Wai Ha Lee May 01 '15 at 23:23