Search code examples
javaregexlookbehind

(?<=#!)(\\w+\\.*\\w+)+ doesn't match #!super.compound.key3


I wrote a simple regexp

String s = "#!key1 #!compound.key2 #!super.compound.key3";
Matcher matcher = Pattern.compile("(?<=#!)(\\w+\\.*\\w+)+").matcher(s);
while (matcher.find()) {
  System.out.println(matcher.group());
}

which results in

ACTUAL

key1
compound.key2
super.compound

and I am wondering why it matches super.compound, but not super.compound.key3 as I expected.

EXPECTED

key1
compound.key2
super.compound.key3

Any improvements to the regexp would be welcomed.


Solution

  • You need to use

    (?<=#!)\w+(?:\.\w+)*
    

    See the regex demo and the regex graph:

    enter image description here

    Java test:

    String s = "#!key1 #!compound.key2 #!super.compound.key3";
    Matcher matcher = Pattern.compile("(?<=#!)\\w+(?:\\.\\w+)*").matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
    // => [key1, compound.key2, super.compound.key3]