Search code examples
androidregexregular-language

Why does the following Pattern not work for all OS versions?


Having the following regex tested on https://regex101.com/r/Q6lTN8/1

Pattern pattern = Pattern.compile("(?<name>\\b\\w+\\b)\\s*=\\s*(?<value>\"[^\"]*\"|'[^']*'+)");

with this input text

id='1019' name='Beer' color='#e7c705'

Works well on Android versions > 6.0, but produces the following crash on Android 5.1

 Process: pro.kleinod.socialapp, PID: 19517

          java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 4:
                                                                    (?<name>\b\w+\b)\s*=\s*(?<value>"[^"]*"|'[^']*'+)

What could be the problem?


Solution

  • Capture groups using .*? instead of with <name> or <value>, This way, you will avoid PatternSyntaxException:

    String regex = "(.*?\\b\\w+\\b)\\s*=\\s*(.*?\"[^\"]*\"|'[^']*'+)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher("id='1019' name='Beer' color='#e7c705'");
    while(matcher.find()) {
        Log.e("TAG", matcher.group());
    }
    

    Tested and working fine on Android 5.1.