解码并替换 Java 中字符串中的十六进制值

Decode and replace hex values in a string in Java

我在 Java 中有一个字符串,它包含正常字符下方的十六进制值。它看起来像这样:

String s = "Hello\xF6\xE4\xFC\xD6\xC4\xDC\xDF"

我想要的是将十六进制值转换为它们所代表的字符,所以它看起来像这样:

"HelloöäüÖÄÜß"

有没有办法用它们代表的实际字符替换所有十六进制值?

我可以用这个实现我想要的,但是我必须为每个字符做一行并且它不包括未例外的字符:

indexRequest = indexRequest.replace("\xF6", "ö");
indexRequest = indexRequest.replace("\xE4", "ä");
indexRequest = indexRequest.replace("\xFC", "ü");
indexRequest = indexRequest.replace("\xD6", "Ö");
indexRequest = indexRequest.replace("\xC4", "Ä");
indexRequest = indexRequest.replace("\xDC", "Ü");
indexRequest = indexRequest.replace("\xDF", "ß");

我会遍历每个字符以找到“\”,而不是跳过一个字符并使用接下来的两个字符启动一个方法。 而不仅仅是使用 Michael Berry 的代码 这里: Convert a String of Hex into ASCII in Java

您可以使用正则表达式 [xX][0-9a-fA-F]+ 来识别字符串中的所有十六进制代码,使用 Integer.parseInt(matcher.group().substring(1), 16) 将它们转换为相应的字符并在字符串中替换它们。下面是它的示例代码

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HexToCharacter {
public static void main(String[] args) {
    String s = "HelloxF6xE4xFCxD6xC4xDCxDF";
    StringBuilder sb = new StringBuilder(s);
    Pattern pattern = Pattern.compile("[xX][0-9a-fA-F]+");
    Matcher matcher = pattern.matcher(s);
    while(matcher.find()) {
        int indexOfHexCode = sb.indexOf(matcher.group());
        sb.replace(indexOfHexCode, indexOfHexCode+matcher.group().length(), Character.toString((char)Integer.parseInt(matcher.group().substring(1), 16)));
    }
    System.out.println(sb.toString());
}

}

我已经使用您的字符串测试了这个正则表达式模式。如果您还有其他测试用例,那么您可能需要相应地更改正则表达式

public static void main(String[] args) {
    String s = "Hello\xF6\xE4\xFC\xD6\xC4\xDC\xDF\xFF ";

    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile("\\x[0-9A-F]+");
    Matcher m = p.matcher(s);
    while(m.find()){           
        String hex = m.group();            //find hex values            
        int    num = Integer.parseInt(hex.replace("\x", ""), 16);  //parse to int            
        char   bin = (char)num;            // cast int to char
        m.appendReplacement(sb, bin+"");   // replace hex with char         
    }
    m.appendTail(sb);
    System.out.println(sb.toString());
}