Regular expression to get a string from parentheses?

I have the following line:

"The Girl with the Dragon Tattoo (LISBETH)"

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

So far I have come to the following:

    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 do you get away from these brackets?

Thank!

+3


source to share


3 answers


Use look and feel and look ahead then you don't need to use / access groups

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

      



Those looking behind / forwards don't match, they just "check", so these brackets won't be part of the match.

+3


source


Use this pattern: \\((.+?)\\)

and then get 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");
    }
}

      

+10


source


You are really close, just change group()

, start()

and the end()

calls are on group(1)

, start(1)

and end(1)

since you already have it in the "relevant group".

Quoted from the api:

public String group ()

Returns the input subsequence that matches the previous match.

and

public String group (int group)

Returns the input subsequence that was captured by this group during a previous match operation.

+3


source







All Articles