Reputation: 19
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!
Upvotes: 1
Views: 834
Reputation: 626794
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})
.Upvotes: 2