Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse float values from string using REGEX in java

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

like image 945
vishal sharma Avatar asked Dec 15 '15 13:12

vishal sharma


People also ask

Can we parse string in to float?

We can convert String to float in java using Float. parseFloat() method.

Can I convert string to float in java?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do I match a float number?

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).


1 Answers

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

like image 122
Avinash Raj Avatar answered Oct 24 '22 17:10

Avinash Raj