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

2019-08-03 21:27发布

I'm new in regex..

How can I parse the string through regex

Balance 123,45 p.

to double 123.45

5条回答
相关推荐>>
2楼-- · 2019-08-03 21:45
(\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 :)

查看更多
ら.Afraid
3楼-- · 2019-08-03 21:49

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

查看更多
Evening l夕情丶
4楼-- · 2019-08-03 21:52

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

This works in IntelliJ IDEA

查看更多
劫难
5楼-- · 2019-08-03 21:57
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)));
        }   
    }   
}
查看更多
Ridiculous、
6楼-- · 2019-08-03 21:58

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);
查看更多
登录 后发表回答