1

I'm searching for a "color=number,number,number" and get the "number,number,number" part using regex but when I put the regex pattern,

I get: Regular expression '"\bcolor=\b\K\w\d,\d*,\d*"' is malformed: Illegal/unsupported escape sequence*

Here is the code:

    Pattern p = Pattern.compile("\\bcolor=\\b\\K\\w\\d*,\\d*,\\d*");
    Matcher m = p.matcher(url);
    if(m.find()){
        return m.group(0);
    }
    else {
        return "0,0,0";
    }

I also tried:

    "\\bcolor=\\b\\\\K\\w\\d*,\\d*,\\d*"

and:

    "\\\\bcolor=\\\\b\\\\K\\\\w\\\\d*,\\\\d*,\\\\d*"

The above compiles but doesn't get the desired result.

How can I fix this? Thanks!

1
  • 1
    Does Java even support \K? Commented Apr 20, 2018 at 9:30

1 Answer 1

2

The \K match reset operator is not supported by the regex engine in Android. You can safely use a capturing group around the part of the regex you want to extract and then grab it using .group(1):

Pattern p = Pattern.compile("\\bcolor=(\\w\\d*,\\d*,\\d*)");
Matcher m = p.matcher(url);
if(m.find()){
    return m.group(1);
}
else {
    return "0,0,0";
}

Note you do not need the second \b word boundary as it is implicit between a = (non-word char) and \w (matches a word char).

Details

  • \bcolor= - color= as a whole word
  • (\w\d*,\d*,\d*) - Capturing group #1: a word char, 0+ digits, and 2 occurrences , followed with , and 0+ digits. You may even write it as (\\w\\d*(?:,\\d*){2}).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.