Formatting string with Regex in java, how do I convert captured group to special character? -


i have set of commands include hidden characters, written in text file. 1 one, read , sent server execute commands.

its important special characters formatted properly, cannot written in text file "\u0002", example, interpreted "\u0002", , not <stx> character looking for.

what i've done, therefore, write them in text file under format:

$'\x02'test$'\x03' 

and i've written regex in java extract numerical values, so:

"\\$'\\\\x(\w\w)'".  

(note escape characters, escape $ , \)

my question is: how can grab hexadecimal characters (\w\w), , convert them unicode character in string, ideally using string.format?

i know i'm able physically grab characters using "$1", "(\w\w)" first , group in each regex pattern. however, i'm having issues conversion. i've tried following:

string.replaceall("\\$'\\\\x(\w\w)'", character.tostring((char)integer.parseint("$1"))); 

but i'm having issues integer.parseint("$1") part, $1 being interpreted string "$1", , not captured group (for example, 02).

as quick workaround, i've implemented workaround each case need, works. (example: string.replace("\\$'\\\\x(02)'", character.tostring((char) (int)0x0002)) ). however, terrible form, , not @ effective parsing case.

if me , point me towards documentation / explanation why $1 interpreted "$1" , not captured group, solution/workaround, appreciated.

edit:

thank nhahtdh below. answer correct, although made 1 small modification:

    static string handleescape(string input) {      pattern p = pattern.compile("\\$'\\\\x(\\w\\w)'");     matcher m = p.matcher(input);      stringbuffer result = new stringbuffer();      while (m.find()) {         m.appendreplacement(result, character.tostring((char) integer.valueof(m.group(1), 16)));     }      m.appendtail(result);      return result.tostring(); } 

i changed integer.parseint(m.group(1)) integer.valueof(m.group(1), 16), correctly convert correct string associated hexadecimal value.

since need manipulate matched text before replacement, need use low-level api in matcher class perform matching , replacement manually.

static string handleescape(string input) {      pattern p = pattern.compile("\\$'\\\\x(\\w\\w)'");     matcher m = p.matcher(input);      stringbuffer result = new stringbuffer();      while (m.find()) {         m.appendreplacement(result,             character.tostring((char) integer.parseint(m.group(1), 16)));     }      m.appendtail(result);      return result.tostring(); } 

Comments