Marcin
Marcin

Reputation: 5579

price regex help

how to make regex below to detect also prices like just £7 not only everything > 9

/\d[\d\,\.]+/is

thanks

Upvotes: 0

Views: 175

Answers (3)

nonopolarity
nonopolarity

Reputation: 150986

to match a single digit, you can change it to

/\d[\d,.]*/

the + means require one or more, so that's why the whole thing won't match just a 7. The * is 0 or more, so an extra digit or , or . becomes optional.


The longer answer might be more complicated. For example, in the book Regular Expression Cookbook, there is an excerpt: (remove the ^ and $ if you want it to match the 2 in apple $2 each) but note that when the number is 1000 or more, the , is needed. For example, the first regex won't match 1000.33

(unsourced image from a book removed)

Upvotes: 3

CtRanger
CtRanger

Reputation: 177

You might look at a regex more like the following.

/(?:\d+[,.]?\d*)|(?:[,.]\d+)/

Test Set:

5.00
$7.00
6123.58
$1
.75

Result Set:

[0] => 5.00
[1] => 7.00
[2] => 6123.58
[3] => 1
[4] => .75

EDIT: Additional Case added

Upvotes: 0

Your expression would allow 123...3456... I think you might want something like (£|$|€)?\d\d+((,|.)\d{2})?

This will require the source have a currency symbol, and two digits for cents with a separator.

Upvotes: 0

Related Questions