Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java RegEx: Just get a part of the matcher group

Tags:

java

regex

I have a regex in Java:

Pattern pattern = Pattern.compile(<string>text</string><string>.+</string>);
Matcher matcher = pattern.matcher(ganzeDatei);
while (matcher.find()) {
    String string = matcher.group();
    ...

This works fine, but the output is something like

<string>text</string><string>Name</string>

But I just want this: Name

How can I do this?

like image 568
Tobias Avatar asked Nov 10 '10 09:11

Tobias


2 Answers

Capture the text you want to return by wrapping it in parenthesis, so in this example your regex should become

<string>text</string><string>(.+)</string>

Then you can access the text that matched between the parenthesis with

matcher.group(1)

The no-arg group method you are calling, returns the entire portion of the input text that matches your pattern, whereas you want just a subsequence of that, which matches a capturing group (the parenthesis).

like image 60
Andrzej Doyle Avatar answered Oct 09 '22 22:10

Andrzej Doyle


Then do this:

Pattern pattern = Pattern.compile(<string>text</string><string>(.+)</string>);
        Matcher matcher = pattern.matcher(ganzeDatei);
        while (matcher.find()) {
            String string = matcher.group(1);
            ...

Reference:

  • Java Tutorial: Regex
  • Pattern JavaDoc: Capturing Groups
  • Matcher JavaDoc: Matcher.group(n)
  • Matcher JavaDoc: Matcher.group()
like image 30
Sean Patrick Floyd Avatar answered Oct 09 '22 22:10

Sean Patrick Floyd