tags:

views:

67

answers:

3

Hi,

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

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

thanks

A: 

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.

FrustratedWithFormsDesigner
ok to be frank I would like to be able to use it with things like USD8 for example
Marcin
Probably {1,2}, or {1,3} if other currencies need to be supported, is better.
Alin Purcaru
@Marcin update your question please.
Alin Purcaru
+3  A: 

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)

動靜能量
This matches `12,.3,.4,.`
ar
thank you very much, this is what I have needed
Marcin
@Will, you removed the image because it is copyrighted material? Isn't a short excerpt usually ok? (it probably help sell the book too)
動靜能量
Sure, its okay to excerpt from a book. You didn't say what book it was, however.
Will
A: 

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

CtRanger