Java正则表达式创建问题

时间:2014-08-14 12:50:16

标签: java regex

我一直在使用正则表达式一段时间,但最近却不得不为此创建表达式;

'余额:$ [此处变量]'

以下是一些可能的例子:

Balance: $10000
Balance: $1000
Balance: $100
Balance: $10
Balance: $1
Balance: $0.1
Balance: $0.10
Balance: $0.01 // Of course all these could be random numbers like 0.06, 10240 etc...

我知道这很简单,但由于某些原因我无法做到正确。

我需要的只是我需要使用的模式'代码',这让我发疯!提前谢谢!

5 个答案:

答案 0 :(得分:2)

正则表达式的问题在于它试图匹配正则表达式语言本身使用的字符,即元字符。这些角色需要转义,如下所示:

"Balance: \\$(\\d+(?:[.]\\d+)?)"

请注意使用两个反斜杠,尽管正则表达式引擎只需要一个。第二个斜杠是因为该字符是Java字符串文字的一部分,它也使用反斜杠来转义字符。

最后,\\d+周围的括号(表示"一个或多个数字")围绕整个数字创建一个捕获组(与周围的非捕获组(?:)不同小数部分)。

答案 1 :(得分:1)

这是您要寻找的表达方式:

Balance: \$(\d+(?:\.\d+)?)

在Java中使用它时,需要转义反斜杠:

"Balance: \\$(\\d+(?:\\.\\d+)?)"

答案 2 :(得分:1)

试试这个正则表达式:

   public static void main(String[] args) {
        String s = "Balance: $10000.003";
        System.out.println(s.matches("Balance: \\$\\d+(\\.\\d+)?$"));
    }

O / P:

true

其他输入/输出:

“余额:10000美元”; - >真

“余额:10000美元。”; - 假

“余额:1美元”; - >真

答案 3 :(得分:0)

Pattern pattern = Pattern.compile("Balance: \\$([0-9]*(?:\\.[0-9]*)?)");

答案 4 :(得分:0)

您可以使用以下Pattern

String[] input = {
        "Balance: $10000",
        "Balance: $1000",
        "Balance: $100",
        "Balance: $10",
        "Balance: $1",
        "Balance: $0.1",
        "Balance: $0.10",
        "Balance: $0.01"
};
//                            | preceded by (escaped) "$"
//                            |      | any 1 or more digit or dot
//                            |      | 
Pattern p = Pattern.compile("(?<=\\$)[\\d.]+");
for (String s: input) {
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.printf("For input \"%s\", found \"%s\".%n", s, m.group());
    }
}

<强>输出

For input "Balance: $10000", found "10000".
For input "Balance: $1000", found "1000".
For input "Balance: $100", found "100".
For input "Balance: $10", found "10".
For input "Balance: $1", found "1".
For input "Balance: $0.1", found "0.1".
For input "Balance: $0.10", found "0.10".
For input "Balance: $0.01", found "0.01".