有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android正则表达式模式使用获取金额$

我试图从这个字符串中获取当前金额,但我只想要双倍

String total = "Your current total is +$35.25";

我已经尝试过这段代码,但是$表示行尾,并且它总是返回0.00,所以我如何才能只得到35.25

double amount = getNumberFromString("(\\$\\d\\d.?\\d?\\d?)\\s?[^Xx]?", total);

public double getNumberFromString(String value, final String s)
{
    double n = 0.0;
    Matcher M = Pattern.compile(value).matcher(s);

    while (((Matcher)M).find())
    {
        try {
            n = Double.parseDouble(((Matcher)M).group(1));
            //Log.e(TAG, "Number is : " + ((Matcher)M).group(1));
        }
        catch (Exception ex) {
            n = 0.0;
        }
    }

    return n;
}

共 (2) 个答案

  1. # 1 楼答案

    我尝试了这个正则表达式,它返回了一个数字,尽管它没有考虑其他的格式化字符,比如“,”表示千分位

    另外,如果符号可以是负数,则可以用[\\+-]替换'\\+'

    double amount = getNumberFromString("^Your current total is \\+\\$(\\d+\\.\\d{2})$", total);
    
  2. # 2 楼答案

    您的代码正在引发异常,因为您的正则表达式正在捕获组#1中的非数字$。还要注意,您的代码正在进行可以避免的不必要的强制转换

    以下代码应该适用于您:

    String total = "Your current total is +$35.25"; 
    
    double amount = getNumberFromString("\\$(\\d+(?:\\.\\d+)?)", total);
    
    public double getNumberFromString(String value, final String s) {
        double n = 0.0;
        Matcher m = Pattern.compile(value).matcher(s);
    
        while (m.find()) {
            try {
                n = Double.parseDouble(m.group(1));
            }
            catch (Exception ex) {
                n = 0.0;
            }
        }
        return n;
    }