2

I'm doing some regex to split some Strings and extract both Unicode and normal escapes out of them (basically any escape accepted by Java), and then I want to parse them through a method.

This all works fine, however now I am at the point where once these escapes have been received, I want to transform them into their actual escape. For example, \n is literally converted into a newline.

I know I can use Apache's StringEscapeUtils, but I don't agree with their license for multiple reasons, and would rather be able to do it myself anyway.

From my understanding, I can simply do something like this:

switch (character) {
case 'n': return '\n';
case 't': return '\t';
default:  return '\0';
}

But I want to be able to parse things like \0345346 and \u3456, which Java will accept as valid entries, without writing every, single possible combination. I can regex these things just fine, but I want to be able to parse them into their literal values.

Is there any way I can acheive this?

1 Answers1

0

This can easily be done by abusing the Properties class, which will actually parse String data and format correctly for you.

private char escapeCharacter(String data) {
    Properties p = new Properties();
    try {
        p.load(new StringReader("key=" + data));
    } catch (IOException e) {
        e.printStackTrace();
        return '\0';
    }
    return p.getProperty("key").charAt(0);
}

This will take in an escape code as a String, load it into the properties, parse it, and return the corrected char.

The function supports Unicode escapes and conventional escapes, as the question requests.