I'm new in regex..
How can I parse the string through regex
Balance 123,45 p.
to double
123.45
I'm new in regex..
How can I parse the string through regex
Balance 123,45 p.
to double
123.45
You can use String.split() with space
as a delimilter and than use String.replaceAll() to replace ,
with .
.
After that use parseDouble.It returns,
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
String number = "Balance 123,45 p.";
String[] number_array = number.split(" ");
String str = (number_array[1].replaceAll(",","."));
double d = Double.parseDouble(str);
System.out.println(d);
Output = 123.45
Note: Not a Regex based solution.
To me it seems that the String that you are getting is from a locale where decimal separator is ,
instead of .
, you can just do something like this:
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
Number n = nf.parse("123,45");
Double d = n.doubleValue();
System.out.print(d);
(\d*(,\d+)?)
This will match zero or more numbers followed by optionally a comma and one or more numbers. e.g: 1,2345; 123; 12,34; ,25 (leading zero may be omitted)
You can then replace the comma with a dot (string.replace(',', '.')
) and do what you want with it :)
Search for Balance (\d*),(\d*) p\.
Replace with double \$1.\$2
This works in IntelliJ IDEA
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.Double;
public class RegExpTest {
public static void main(String[] args) {
String str = "Balance 123,45 p.";
String p = "Balance (\\d+),(\\d+) p";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(str);
if (matcher.find()){
System.out.println(Double.parseDouble(matcher.group(1)+"."+matcher.group(2)));
}
}
}