使用正则表达式查找2个括号之间的数字

时间:2013-07-13 04:53:21

标签: java regex

在一行中我可能有(123,456) 我想在java中使用模式找到它。我做的是:

Pattern pattern = Pattern.compile("\\W");
Matcher matcher = pattern.matcher("(");
while (matcher.find()) {
      System.out.print("Start index: " + matcher.start());
      System.out.print(" End index: " + matcher.end() + " ");
}

输入:This is test (123,456) 输出:Start index: 0 End index: 1 ( 为什么?

2 个答案:

答案 0 :(得分:4)

我不确定\W将如何匹配它。 \W匹配非单词字符。

你还必须逃避那些反斜杠。

需要对圆括号进行转义,因为默认情况下它们用于分组。

也许你的正则表达式是

Pattern pattern = Pattern.compile("\\([,\\d]+\\)");
Matcher matcher = pattern.matcher(inputString);

while (matcher.find()) {
    String matched = matcher.group();
    //Do something with it  
}

<强>解释

\\(     # Match (
[,\\d]+ # Match 1+ digits/commas. Don't be surprised if it matches (,,,,,,)
\\)     # Match )

答案 1 :(得分:1)

要在一行中完成:

String num = str.replaceAll(".*\\(([\\d,]+)\\).*", "$1");
相关问题