Extracting string from within round brackets in Java with regex

后端 未结 4 1188
迷失自我
迷失自我 2020-12-07 04:46

I\'m trying to extract a string from round brackets.
Let\'s say, I have John Doe (123456789) and I want to output the string 123456789 only.

相关标签:
4条回答
  • 2020-12-07 05:09
    String str="John Doe (123456789)";
    System.out.println(str.substring(str.indexOf("(")+1,str.indexOf(")")));
    

    Here I'm performing string operations. I'm not that much familiar with regex.

    0 讨论(0)
  • In Java, you need to use

    String pattern = "\\(([^()]+)\\)";
    

    Then, the value you need is in .group(1).

    String str = "John Doe (123456789)";
    String rx = "\\(([^()]+)\\)";
    Pattern ptrn = Pattern.compile(rx);
    Matcher m = ptrn.matcher(str);
    while (m.find()) {
      System.out.println(m.group(1));
    }
    

    See IDEONE demo

    0 讨论(0)
  • 2020-12-07 05:18

    this works for me :

    @Test
    public void myTest() {
        String test = "test (mytest)";
        Pattern p = Pattern.compile("\\((.*?)\\)");
        Matcher m = p.matcher(test);
    
        while(m.find()) {
            assertEquals("mytest", m.group(1));
        }
    }
    
    0 讨论(0)
  • 2020-12-07 05:28

    You need to escape brackets in your regexp:

        String in = "John Doe (123456789)";
    
        Pattern p = Pattern.compile("\\((\\d*)\\)");
        Matcher m = p.matcher(in);
    
        while (m.find()) {
            System.out.println(m.group(1));
        }
    
    0 讨论(0)
提交回复
热议问题