juckky
juckky

Reputation: 503

Unsure of regex for numeric which can include unit chars

I have the following regex which only allows numerics

^[0-9]+$

Trouble is, I also need to allow the user to enter a decimal aspect and unit

So these would all need to be valid

123

123456789

1.25M

1.2K

1.5B

12345.53M

0.5M

If anyone can help I'd be most grateful

Upvotes: 0

Views: 53

Answers (2)

James Newton
James Newton

Reputation: 7104

Does this work for all your cases, and exclude all the cases that should not match?

^\d*\.?\d+[GMKB]?$

Explanation:

^\d*    - Start with zero or more digits
\.?     - Allow a decimal point, if there is one
\d+     - Require at least one digit (which might be after a decimal point)
[GMKB]? - Allow one of these 4 letters
$       - Don't allow any more characters after this sequence

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158130

Since you didn't specified one I assume you are using perl compatible regex engine. You can use this:

/^([0-9]*\.)?[0-9]+(B|K|M|G)?$/

I also assume that numbers like 0.1 can be written like .1. Having the units encapsulated in capturing group (B|K|M|G) makes it easy to extract it from results afterwards.

You can test the regex here

Upvotes: 0

Related Questions