Java和正则表达式、子字符串

Java和正则表达式、子字符串,java,regex,substring,Java,Regex,Substring,谈到正则表达式,我完全迷路了。 生成的字符串如下: Your number is (123,456,789) 如何筛选出123456789?您可以使用此正则表达式提取包含逗号的数字 \(([\d,]*)\) 第一个被抓获的小组将有你的对手。代码将如下所示 String subjectString = "Your number is (123,456,789)"; Pattern regex = Pattern.compile("\\(([\\d,]*)\\)"); Matcher regex

谈到正则表达式,我完全迷路了。 生成的字符串如下:

Your number is (123,456,789)

如何筛选出
123456789

您可以使用此正则表达式提取包含逗号的数字

\(([\d,]*)\)
第一个被抓获的小组将有你的对手。代码将如下所示

String subjectString = "Your number is (123,456,789)";
Pattern regex = Pattern.compile("\\(([\\d,]*)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    String resultString = regexMatcher.group(1);
    System.out.println(resultString);
}
正则表达式的解释

"\\(" +          // Match the character “(” literally
"(" +           // Match the regular expression below and capture its match into backreference number 1
   "[\\d,]" +       // Match a single character present in the list below
                      // A single digit 0..9
                      // The character “,”
      "*" +           // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
")" +
"\\)"            // Match the character “)” literally
这将使您开始

尝试

"\\(([^)]+)\\)"

您将看到第一组是整个字符串,接下来的3组是您的数字

String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");                    
或者,您可以通过执行以下操作加快更换速度:

str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");                    

另外:当你说“过滤掉”时,你的意思是你想以“你的号码是()”结束,还是你想以号码结束?很抱歉,忘了提到生成的字符串可以有不同的大小,否则使用String.substring方法很容易使用开始索引和停止索引对其进行子串,但这是不可能的,因为字符串的大小不同。但是格式总是
你的号码是(xxx,xxx,xxx,xx,xxx,xxx)
为什么确切的已知字符串使用“(”的索引搜索?当你可以使用其他内容时,不要使用正则表达式。这在问题中没有指定。谢谢你给出了一个非常好的答案!我也在寻找一个好的参考,所以谢谢你的链接!
private void showHowToUseRegex()
{
    final Pattern MY_PATTERN = Pattern.compile("Your number is \\((\\d+),(\\d+),(\\d+)\\)");
    final Matcher m = MY_PATTERN.matcher("Your number is (123,456,789)");
    if (m.matches()) {
        Log.d("xxx", "0:" + m.group(0));
        Log.d("xxx", "1:" + m.group(1));
        Log.d("xxx", "2:" + m.group(2));
        Log.d("xxx", "3:" + m.group(3));
    }
}
String str="Your number is (123,456,789)";
str = str.replaceAll(".*\\((.*)\\).*","$1");                    
str = str.replaceAll(".*\\(([\\d,]*)\\).*","$1");