2

I have the a string in Java which contains hex values beneath normal characters. It looks something like this:

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

What I want is to convert the hex values to the characters they represent, so it will look like this:

"HelloöäüÖÄÜß"

Is there a way to replace all hex values with the actual character they represent?

I can achieve what I want with this, but I have to do one line for every character and it does not cover unexcepted characters:

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", "ß");
schande
  • 576
  • 12
  • 27

3 Answers3

3
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());
} 
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

I would loop through every chacter to find the '\' and than skip one char and start a methode with the next two chars. And than just use the code by Michael Berry here: Convert a String of Hex into ASCII in Java

Andyman
  • 1
  • 1
0

You can use a regex [xX][0-9a-fA-F]+ to identify all the hex code in your string, convert them to there corresponding character using Integer.parseInt(matcher.group().substring(1), 16) and replace them in string. Below is a sample code for it

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());
}

}

I have tested this regex pattern using your string. If there are other test-cases that you have in mind, then you might need to change regex accordingly

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41