从String中提取一个数字

时间:2014-03-11 00:39:06

标签: java regex

我使用以下方法从字符串中提取金额。

strAmountString = "$272.94/mo for 24 months Regular Price -$336.9"

public static String fnAmountFromString(String strAmountString) {
    String strOutput = "";

    Pattern pat = Pattern.compile("\\$(-?\\d+.\\d+)?.*");
    Matcher mat = pat.matcher(strAmountString);

    while(mat.find())
        strOutput = mat.group(1);

    return strOutput;
}

现在我必须从字符串中提取字符串272.94,并且上面的函数工作正常。

但是当我必须从字符串272.94中提取strAmountString = "272.94"时,给我一个空值。

此外,我必须从-336.9

中提取string strAmountString = "$272.94/mo for 24 months Regular Price -$336.9"金额

3 个答案:

答案 0 :(得分:1)

尝试使用272.94时,您的第一个问题与正则表达式的要求有关,因为要求String$引导}

您可以将$作为可选组的一部分,例如((\\$)?\\d+.\\d+),它将匹配272.94$272.94,但不会匹配-$336.9直接,它将匹配$336.9

因此,在您的示例中,您可以使用现在匹配((-)?(\\$)?\\d+.\\d+)的{​​{1}} ...

就我个人而言,我可能会使用-$336.9((-)?(\\$)?(-)?\\d+.\\d+)-$336.9$-336.9-336.9

下一步是尝试从结果中删除336.9,是的,您可以尝试使用其他正则表达式,但说实话,$会更容易......

注意 - 我的正则表达式知识非常基础,所以可能有更简单的求解

更新了示例

String#replaceAll

哪些输出......

String value = "$272.94/mo for 24 months Regular Price -$336.9";
String regExp = "((-)?(\\$)?(-)?\\d+.\\d+)";

Pattern p = Pattern.compile(regExp);
Matcher matcher = p.matcher(value);
while (matcher.find()) {
    System.out.println(matcher.group());
}

答案 1 :(得分:0)

以下注册表将为您提供两组(第1组和第3组)

(\\$\\d+\\.\\d+)(.*)?(\\-?\\$\\d+\\.\\d+)

答案 2 :(得分:0)

首先,您需要在模式中选择美元符号 - 或者换句话说,它需要存在0次或更多次。使用*限定符。

其次,如果您确定美元金额将始终位于字符串的开头,则可以使用^边界匹配器,它指示该行的开头。

同样,如果您确定最终的金额始终位于该行的末尾,则可以使用$边界匹配器。

在此处查看更多详情:http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

在此处测试您的模式:http://www.regexplanet.com/advanced/java/index.html