javaregexlookbehind

How to capture lookbehind using java


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


Solution

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