简体   繁体   中英

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!

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM