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!
source to share
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");
}
}
source to share
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.
source to share