0

I try to work on a translator, in Java, that use regex for configuring it.

I have the following hex string : 31353333303430353431455232335445303031

and I must convert it and find ascii string like this : 1533040541ER23TE001

My question is can I use regex to convert an hex string to an ascii string.

Fred37b
  • 822
  • 2
  • 10
  • 29
  • 1
    Doesn't seem like a regex task to me. Why do you need to use regex for this? – 41686d6564 stands w. Palestine Aug 31 '18 at 13:52
  • For getting a generic translator in my program, so I can re-configure my translator in changing the regex. – Fred37b Aug 31 '18 at 13:53
  • Possible duplicate of [How to parse a string of hex into ascii equivalent in Swift 2](https://stackoverflow.com/questions/31816182/how-to-parse-a-string-of-hex-into-ascii-equivalent-in-swift-2) – Sinto Aug 31 '18 at 13:55
  • I don't what your trying to do is possible using regex _solely_. AFAIK, there's nothing in regex that allows you to change the base of a number from hex to decimal, _let alone the corresponding character in the ascii table_. – 41686d6564 stands w. Palestine Aug 31 '18 at 13:58
  • As others have said, a regex is a tool for matching text, it doesn't have any way to *change* text by itself. A regexp-replace function can do that by combining the regex matching with a string manipulation, but how that works depends on the function. Some only allow you to provide a replacement string or pattern, others allow running arbitrary code for each match. Which features do your translator have for reacting to the matches of a regex? – lrn Aug 31 '18 at 15:07

1 Answers1

0

Well, you CAN use regex for this, but I would say that it is a bit of an overkill.

The best use for regex here would be to remove all possible non-hex characters from the string with:

String hexStr = subjectString.replaceAll("[^0-9A-Fa-f]", "");

Anyway, here's how you could convert the hex string into plain ASCII:

With RegEx:

StringBuilder output = new StringBuilder("");
Pattern regex = Pattern.compile("[0-9A-Fa-f]{2}");
Matcher regexMatcher = regex.matcher(hexStr);
while (regexMatcher.find()) {
    output.append((char) Integer.parseInt(regexMatcher.group(), 16));
}

output.toString();

Without RegEx:

StringBuilder output = new StringBuilder("");

for (int i = 0; i < hexStr.length(); i += 2) {
    String str = hexStr.substring(i, i + 2);
    output.append((char) Integer.parseInt(str, 16));
}

output.toString();
Theo
  • 57,719
  • 8
  • 24
  • 41