-1

I am trying to capture text that is matched by lookbehind.

My code :

private static final String t1="first:\\\w*";
private static final String t2="(?<=\\w+)=\\".+\\"";
private static final String t=t1+'|'+t2;

Pattern p=Pattern.compile(t);
Matcher m=p.matcher("first:second=\\"hello\\"");
while(m.find())
      System.out.println(m.group());

The output:
first:second
="hello"

I expected:
first:second
second="hello"

How can I change my regex so that I could get what I expect.

Thank you

Joseph
  • 17
  • 5
  • 2
    By not using a lookbehind. Lookaheads and lookbehinds are by definition not part of the captured results. – Rob Spoor Mar 28 '22 at 17:07
  • Did you actually try to compile your example?? Do yourself a favour and give us a [mre] so you can test better for yourself as well. – cyberbrain Mar 28 '22 at 17:30

1 Answers1

0

Why don't you just use one regex to match it all?

(first:)(\w+)(=".+")

And then simply use one match, and use the groups 1 and 2 for the first expected row and the groups 2 and 3 for the second expected row.

I modified your example to be compilable and showing my attempt:

package examples.stackoverflow.q71651411;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Q71651411 {
  public static void main(String[] args) {
    Pattern p = Pattern.compile("(first:)(\\w+)(=\".+\")");
    Matcher m = p.matcher("first:second=\"hello\"");
    while (m.find()) {
      System.out.println("part 1: " + m.group(1) + m.group(2));
      System.out.println("part 2: " + m.group(2) + m.group(3));
    }
  }
}
cyberbrain
  • 3,433
  • 1
  • 12
  • 22