regex help: Balance 123,33 p. => 123.33 (double)

霸气de小男生 提交于 2019-12-13 02:59:34

问题


I'm new in regex..

How can I parse the string through regex

Balance 123,45 p.

to double 123.45


回答1:


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




回答2:


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



回答3:


(\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 :)




回答4:


Search for Balance (\d*),(\d*) p\. Replace with double \$1.\$2

This works in IntelliJ IDEA




回答5:


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)));
        }   
    }   
}


来源:https://stackoverflow.com/questions/9128531/regex-help-balance-123-33-p-123-33-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!