Adrian K.
Adrian K.

Reputation: 118

Java: Regular Expression not matching?

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)

Upvotes: 2

Views: 335

Answers (2)

Mena
Mena

Reputation: 48444

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.

Upvotes: 1

Akhil Job
Akhil Job

Reputation: 419

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.

Upvotes: 0

Related Questions