RegEx - How to get a price?

How to extract the amount in dollars from the next line

"some text will go here and more, and then there will be a price of $ 34.03, but that does not mean that the line will end"

I want to extract $ 34.03 ... I also want to extract if there are no cents

"some text will go here and more, and then there will be a price of $ 34, but that does not mean that the line will end"

Here I want to extract $ 34

+4
php regex
source share
5 answers

I am not a regex guru, but I was able to pick up the following with RegExr .

/(\$[0-9]+(\.[0-9]{2})?)/ 

Corresponds to $35.03 and $35 . To accept formats like $35,000.52 you need to enable

 /(\$[0-9,]+(\.[0-9]{2})?)/ 

This could probably be improved, but from my preliminary tests, this works fine.

+17
source share
 '/\$\d+(?:\.\d+)?/' if(preg_match('/\$\d+(?:\.\d+)?/',$text,$matches)){ echo $matches[0]; //which would be $34 or $34.03 } 
+2
source share

Since you are not mentioning a specific regex engine, you may need to slightly modify this value:

 /(\$\d+(\.\d+)?)/ 
+1
source share

How about this regex: \$[0-9.,]+ Or \$([0-9.,]+) To remove $ ?

It's simple, but he does a lot of what you want, he even catches such things: $1,450.8934 or $14.343 .

Of course, the downside would be that he would catch $34.54.23 .

Or if you want to catch only two decimal places: \$[0-9,]+\.[0-9]{2} it will catch part of $5.23 $5.234565 .

You can use it with preg_match or preg_match_all .

+1
source share

I am currently working on a small function that uses a regular expression to get the sum of the price inside a string:

 private static String getPrice(String input) { String output = ""; Pattern pattern = Pattern.compile("\\d{1,3}[,\\.]?(\\d{1,2})?"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { output = matcher.group(0); } return output; } 

it looks like a small price (from 0.00 to 999.99) and a different currency:

$ 12.34 β†’ 12.34

$ 12.34 β†’ 12.34

$ 12.00 β†’ 12.00

$ 12 β†’ 12

12 € β†’ 12

12,11 € β†’ 12,11

12.999 € β†’ 12.99

12.9 € β†’ 12.9

Β£ 999.99 € β†’ 999.99

...

+1
source share

All Articles