3

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!

2
  • What is your input and output? The referenced post shows how to get the Group 1 value. Commented Jul 17, 2015 at 12:01
  • Input is a String and output is also a String. Commented Jul 17, 2015 at 12:02

4 Answers 4

3
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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.