I copied this code from another StackOverflow post. However, I am having some issues with it. The items matching the pattern specified should be replaced but they are not.
The code is:
protected String FixHexValuesInString(String str){
Log.v(TAG, "before fix: "+ str);
Matcher matcher = Pattern.compile("\\\\x([0-9a-f]{2})").matcher(str);
while (matcher.find()) {
int codepoint = Integer.valueOf(matcher.group(1), 16);
Log.v(TAG, "matcher group 0: " + matcher.group(0));
Log.v(TAG, "matcher group 1: " + matcher.group(1));
str = str.replaceAll(matcher.group(0), String.valueOf((char) codepoint));
}
Log.v(TAG, " after fix: "+ str);
return str;
}
Here an example that I wrote to LogCat:
before fix: 'id': 1268, 'name': 'Reserva de Usos M\xfaltiples de la Cuenca del Lago de Atitl\xe1n-RUMCLA (Atitl\xe1n Watershed Multiple Use Reserve)'
matcher group 0: \xfa
matcher group 1: fa
matcher group 0: \xe1
matcher group 1: e1
matcher group 0: \xe1
matcher group 1: e1
after fix: 'id': 1268, 'name': 'Reserva de Usos M\xfaltiples de la Cuenca del Lago de Atitl\xe1n-RUMCLA (Atitl\xe1n Watershed Multiple Use Reserve)'
Anybody see why this doesn’t work?
You shouldn’t be using
String.replaceAllmethod at all when you are doing regular expression matching and replacement… You should be using the matchers built inMatcher.appendReplacementandMatcher.appendTailmethods like this:Output: