Extracting string from within round brackets in Java with regex

最后都变了- 提交于 2019-11-26 22:11:58

问题


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.

I have found this link and this regex:

/\(([^)]+)\)/g

However, I wasn't able to figure out how to get the wanted result.

Any help would be appreciated. Thanks!


回答1:


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.




回答2:


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));
    }



回答3:


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));
    }
}



回答4:


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



来源:https://stackoverflow.com/questions/31475386/extracting-string-from-within-round-brackets-in-java-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!