Search code examples
javaregexnon-greedy

Java split regex non-greedy match not working


Why is non-greedy match not working for me? Take following example:

public String nonGreedy(){
   String str2 = "abc|s:0:\"gef\";s:2:\"ced\"";
   return str2.split(":.*?ced")[0];
}

In my eyes the result should be: abc|s:0:\"gef\";s:2 but it is: abc|s


Solution

  • The .*? in your regex matches any character except \n (0 or more times, matching the least amount possible).

    You can try the regular expression:

    :[^:]*?ced
    

    On another note, you should use a constant Pattern to avoid recompiling the expression every time, something like:

    private static final Pattern REGEX_PATTERN = 
            Pattern.compile(":[^:]*?ced");
    
    public static void main(String[] args) {
        String input = "abc|s:0:\"gef\";s:2:\"ced\"";
        System.out.println(java.util.Arrays.toString(
            REGEX_PATTERN.split(input)
        )); // prints "[abc|s:0:"gef";s:2, "]"
    }