karla
karla

Reputation: 4606

A regex to get string out of the brackets?

I have the following string:

"The girl with the dragon tattoo (LISBETH)"

and I need to get only the string in the brackets at the end of the input.

So far I came to this:

    public static void main(String[] args) {

    Pattern pattern =
    Pattern.compile("\\({1}([a-zA-Z0-9]*)\\){1}");

    Matcher matcher = pattern.matcher("The girl with the dragon tattoo (LISBETH)");

    boolean found = false;
    while (matcher.find()) {
        System.out.println("I found the text " + matcher.group()
                + " starting at " + "index " + matcher.start()
                + " and ending at index " +
                matcher.end());
        found = true;
    }
    if (!found) {
        System.out.println("No match found");
    }
}

But as a result I get: (LISBETH).

How to get away from those brackets?

Thanks!

Upvotes: 3

Views: 3718

Answers (3)

shift66
shift66

Reputation: 11958

Use this pattern: \\((.+?)\\) and then get the group 1

public static void main(String[] args) {

    Pattern pattern = Pattern.compile("\\((.+?)\\)");
    Matcher matcher = pattern.matcher("The girl with the dragon tattoo (LISBETH)");

    boolean found = false;
    while (matcher.find()) {
        System.out.println("I found the text " + matcher.group(1)
                + " starting at " + "index " + matcher.start()
                + " and ending at index " +
                matcher.end());
        found = true;
    }
    if (!found) {
        System.out.println("No match found");
    }
}

Upvotes: 10

dacwe
dacwe

Reputation: 43504

You are really close, just change group(), start() and end() calls to group(1), start(1) and end(1) since you already have it in a "matching group".

Quoted from the api:

public String group()

Returns the input subsequence matched by the previous match.

And:

public String group(int group)

Returns the input subsequence captured by the given group during the previous match operation.

Upvotes: 3

stema
stema

Reputation: 93036

Use look behind and look ahead, then you don't need to use/access the groups

Pattern.compile("(?<=\\()[a-zA-Z0-9]*(?=\\))");

Those look behind/ahead are not matching, they are just "checking", so those brackets will not be part of the match.

Upvotes: 3

Related Questions