2

I am trying to extract a special sequence out of a String using the following Regular Expression:

[(].*[)]

My Pattern should only match if the String contains () with text between them.

Somehow, i I create a new Pattern using Pattern#compile(myString) and then match the String using Matcher matcher = myPattern.matcher(); it doesn't find anything, even though I tried it on regexr.com and it worked there.

My Pattern is a static final Pattern object in another class (I directly used Pattern#compile(myString).

Example String to match:

save (xxx,yyy)
5
  • You should include part of your code Commented Sep 21, 2016 at 10:16
  • Please say whether you want to match or extract Commented Sep 21, 2016 at 10:21
  • What does doesn't find anything mean? - Are you using matches() or find() ? Commented Sep 21, 2016 at 10:21
  • Also can you mention if you are using matches() or find() Commented Sep 21, 2016 at 10:24
  • Okay guys, was my fault, I fixed it as I literally forgot to use find() Thanks for your help! Commented Sep 21, 2016 at 10:27

2 Answers 2

1

The likely problem here is your quantifier.

Since you're using greedy * with a combination of . for any character, your match will not delimit correctly as . will also match closing ).

Try using reluctant [(].*?[)].

See quantifiers in docs.

You can also escape parenthesis instead of using custom character classes, like so: \\( and \\), but that has nothing to do with your issue.

Also note (thanks esprittn)

  • The * quantifier will match 0+ characters, so if you want to restrict your matches to non-empty parenthesis, use .+? instead - that'll guarantee at least one character inside your parenthesis.
Sign up to request clarification or add additional context in comments.

1 Comment

with [(].*?[)], empty parenthesis like () will be matched so replace * with +
0

Hope the below code helps : its extracts the data between '(' & ')' including them .

String pattern = "\\(.*\\)";
    String line = "save(xx,yy)";
    Pattern TokenPattern = Pattern.compile(pattern);

    Matcher m = TokenPattern.matcher(line);
    while (m.find()) {

        int start = m.start(0);
        int end = m.end(0);

        System.out.println(line.substring(start, end));

    } 

to remove the brackets change 'start' to 'start+1' and 'end' to 'end-1' to change the bounding indexes of the sub-string being taken.

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.