Matching Regular Expression Numbers and Decimals

I need a regex expression that will match the following:

.5 0.5 1.5 1234 

but NOT

 0.5.5 absnd (any letter character or space) 

I have this that satisfies all but 0.5.5

 ^[.?\d]+$ 
+7
source share
5 answers

This is a fairly common task. The easiest way I know to handle this:

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

There are other complications, for example, whether you want to resolve leading zeros or commas or something like that. It can be as hard as you want it to be. For example, if you want to allow the format 1,234,567.89, you can go with this:

 ^[+-]?(\d*|\d{1,3}(,\d{3})*)(\.\d+)?\b$ 

This \b is a word break, but I use it as a hidden way to require at least one digit at the end of a line. So an empty string or one + will not match.

However, keep in mind that regular expressions are not an ideal way to parse numeric strings. . All modern programming languages ​​that I know of have quick, simple, built-in methods for this.

+18
source

No one seems to account for negative numbers. In addition, some of them create a capture group that is not needed. This is the most thorough IMO solution.

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

EDIT: Why downvote?

+10
source

The following should work:

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

This uses a negative result to ensure that less than two characters are left in the string . .

http://www.rubular.com/r/N3jl1ifJDX

+3
source

Here's a much simpler solution that doesn't use any perspectives or delays:

 ^\d*\.?\d+$ 

To clearly understand why this works, read it from right to left:

  • At the end, at least one digit is required.
    7 works
    77 works
    .77 working
    0.77 works
    0. does not work
    empty line not working
  • One period preceding the figure is optional.
    .77 working
    77 works
    ..77 does not work
  • Any number of digits preceding a (optional) period. .77 working
    0.77 works
    0077.77 works
    0077 works

Not using look-ahead and look-behinds has the added benefit of not having to worry about RegEx-based DOS attacks.

NTN

+2
source

This might work:

 ^(?:\d*\.)?\d+$ 
+1
source

All Articles