Answer the question
In order to leave comments, you need to log in
How to extract the price from a string?
There are lines from which you need to isolate the price in the format number-point-fractional part (if any).
$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
Extra:
£999.99€(2) -> 999.99
_ per piece (3) ->
999.99 RUB 999.99 per ton (33) -> 999.99
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;
}
preg_match("\\d{1,3}[,\\.]?(\\d{1,2})?", $str, $matches);
$price = $matches[0];
//Сам я делаю вот так:
preg_match('/\d+\.?\d*/', $str, $matches);
/* но это очень простой код, здесь не учитывается запятая вместо точки
и скорее всего дополнительные примеры не обработаются нормально,
например этот "999,99 Руб. за тонну (33)" */
$price = $matches[0];
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question