Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching numbers and decimals

Tags:

regex

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]+$
like image 741
clestbest Avatar asked Jun 06 '12 19:06

clestbest


People also ask

What is the regex for decimal number?

\d* - 0 or more digits (the decimal part);

How do I match a range of numbers in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What regex syntax is used for matching any number of repetitions?

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.


1 Answers

This is a fairly common task. The simplest way I know of to deal with it is this:

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

There are also other complications, such as whether you want to allow leading zeroes or commas or things like that. This can be as complicated as you want it to be. For example, if you want to allow the 1,234,567.89 format, you can go with this:

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

That \b there is a word break, but I'm using it as a sneaky way to require at least one numeral at the end of the string. This way, an empty string or a single + won't match.

However, be advised that regexes are not the ideal way to parse numeric strings. All modern programming languages I know of have fast, simple, built-in methods for doing that.

like image 174
Justin Morgan Avatar answered Sep 25 '22 08:09

Justin Morgan