Extracting string from within round brackets in Java with regex

坚强是说给别人听的谎言 提交于 2019-11-28 02:22:51
SatyaTNV
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.

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

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

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

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