I want to parse float values from
CallCost:Rs.13.04 Duration:00:00:02 Bal:Rs.14.67 2016 mein Promotion
From above string i need 13.04 and 14.67. I used following regex
Pattern p = Pattern.compile("\\d*\\.\\d+");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(">> " + m.group());
}
But using this i am getting ".13", ".04", ".14", ".67" Thanks in advance
We can convert String to float in java using Float. parseFloat() method.
For converting strings to floating-point values, we can use Float. parseFloat() if we need a float primitive or Float. valueOf() if we prefer a Float object.
$ means "Match the end of the string" (the position after the last character in the string).
Here is a better attempt: [-+]?([0-9]*\. [0-9]+|[0-9]+). This regular expression matches an optional sign, that is either followed by zero or more digits followed by a dot and one or more digits (a floating point number with optional integer part), or that is followed by one or more digits (an integer).
Use \\d+
instead of \\d*
Pattern p = Pattern.compile("\\d+\\.\\d+");
Why?
Because if you use \\d*\\.\\d+
, this should match from the dot exists next to Rs
, since you made the integer part to repeat zero or more times., So it don't care about the integer part.
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With