oprogfrogo
oprogfrogo

Reputation: 2074

Regex Price in a String

I found this regex which finds prices like 1.00 or $1.00. But it also returns true for values that are 3 or more digits long like '365'.

/([\d,]+.\d+)+/i

Is there anyway to modify this regex to return true for all types of prices that are floating point but excludes 3 consecutive digits like '365' or '1000', etc.:

1.00 $1.00

Upvotes: 1

Views: 431

Answers (5)

Town
Town

Reputation: 14906

If you're looking to match prices in a piece of text, such as:

1.00 is a valid price and so are $1.50 and $10.12, but not $200.90 or £1000.10

Then this will return 1.00, $1.50 and $10.12 as matches.

(^|\W{1})\d{1,2}\.\d{2}

Upvotes: 0

TheDude
TheDude

Reputation: 3952

If I am not mistaken, instead of '.', you need to use '\.'. What you have would match anything, while the second matches just the character '.' .

/([\d,]+\.\d+)/

Upvotes: 1

pcofre
pcofre

Reputation: 4066

You can limit the regex parts extension by using {a,b}

\d{1,2}\.\d{2}$

Upvotes: 0

Wrikken
Wrikken

Reputation: 70460

. matches everything, so, escape it:

/([\d,]+\.\d+)+/i

I'd even do this:

/\d{1,3}(,?\d{3})*\.\d+)+/i

Upvotes: 0

Mike Dinescu
Mike Dinescu

Reputation: 55720

This should find all single digit numbers, with decimal points. So:

1.xxx
2.xxx
...
9.xxx

but not

365 or 365.000

/(\d\.\d+)/i

Upvotes: 2

Related Questions