简体   繁体   English

正则表达式ReplaceAll不起作用

[英]Regex ReplaceAll Doesn't Work

I copied this code from another StackOverflow post. 我从另一个StackOverflow帖子中复制了此代码。 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: 这是我写给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.replaceAll method at all when you are doing regular expression matching and replacement... You should be using the matchers built in Matcher.appendReplacement and Matcher.appendTail methods like this: 在进行正则表达式匹配和替换时,您根本不应该使用String.replaceAll方法。您应该使用Matcher.appendReplacementMatcher.appendTail方法中内置的匹配器,如下所示:

public static void main(String[] args) {

    String str = "'id': 1268, 'name': 'Reserva de Usos M\\xfaltiples de " +
                 "la Cuenca del Lago de Atitl\\xe1n-RUMCLA (Atitl\\xe1n " +
                 "Watershed Multiple Use Reserve)'";

    Matcher matcher = Pattern.compile("\\\\x([0-9a-f]{2})").matcher(str);

    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        int codepoint = Integer.valueOf(matcher.group(1), 16);
        matcher.appendReplacement(sb, String.valueOf((char) codepoint));
    }
    matcher.appendTail(sb);

    System.out.println(sb);
}

Output: 输出:

'id': 1268, 'name': 'Reserva de Usos Múltiples de la Cuenca del Lago de Atitlán-RUMCLA (Atitlán Watershed Multiple Use Reserve)'

replaceAll() uses the first parameter as regex. replaceAll()使用第一个参数作为正则表达式。 In your first group, you have \\xfa which is an unescaped \\ . 在您的第一组中,您有\\xfa这是未转义的\\ Try adding a \\ to the beginning of your group. 尝试在组的开头添加一个\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM