the_architecht
the_architecht

Reputation: 25

PHP - Regex on numbers, optional decimals and letter

I'm trying to "validate" some input from a form on the backend but I kinda got stuck with the required regex. Basically, I want to get a number, no leading zeroes, with an optional decimal and an optional case insensitive thousands notation (1,000 = 1k, 1,000,000 = 1m, 1 billion = 1b ...) These should match/validate:

12.39
12.389k
99.1003b
40.1m

These should fail.

0.0
12.00b
1e3
2^5
0xFF
12.6z
asdf

So far I've tried this:

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

It works but I'm thinking maybe someone could solve this a bit more elegantly than I did.

Upvotes: 2

Views: 160

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

[Edit] without thousand separator:

/^(?:[1-9][0-9]*(?:\.[0-9]*[1-9])?|0\.[0-9]*[1-9])[kbmt]?$/i

demo


[Old answer] with thousand separator:

You can do it with:

/^(?:[1-9][0-9]{0,2}(?:(,?)[0-9]{3})?(?:\1[0-9]{3})*(?:\.[0-9]*[1-9])?|0\.[0-9]*[1-9])[kbmt]?$/i

demo

details:

^
(?: # numbers >= 1
    [1-9][0-9]{0,2}
    (?:(,?)[0-9]{3})? # capture an eventual thousand separator
    (?:\1[0-9]{3})*
    # decimal
    (?:\.[0-9]*[1-9])?

  | # numbers < 1
    0\.[0-9]*[1-9]
)[kbmt]?$

Upvotes: 1

Alexander Holman
Alexander Holman

Reputation: 929

The below should be what you're after:

/(\b[1-9][\d\,\.]+([kmbt]?))(\s)/g

It matches 12.00b however... Here is an example of it's use.

Group 1 will contain your exact match.

Upvotes: 0

Rahul Patel
Rahul Patel

Reputation: 5244

Update in REGEX.

Below regex will not leading zero allow special characters and characters without specified for notation.

Below regex will allow decimal and integer with thousand and other notation.

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

Please check working demo : http://www.regexpal.com/?fam=95995

Upvotes: 0

Related Questions