Ryan Leach
Ryan Leach

Reputation: 4470

Escaping dots in java. (StringEscapeUtil)

This is probably a super dumb question, but I can't work out why StringEscapeUtils is behaving in this manner.

It's the second assert that's failing, with the following error:

org.junit.ComparisonFailure: Did not escape correctly Expected :t\.ext Actual :t.ext

Tests

public class ServerDataTest {
    @Test
    public void escape() throws Exception {
        assertEquals("Did not escape correctly", "text", ServerData.escape("text"));
        assertEquals("Did not escape correctly", "t\\.ext", ServerData.escape("t.ext"));
        assertEquals("Did not escape correctly", "te\\\\xt", ServerData.escape("te\\xt"));
        assertEquals("Did not escape correctly", "te\\\\\\.xt", ServerData.escape("te\\.xt"));
    }
}

Escaper utility

private final static Map<CharSequence, CharSequence> ESCAPE_MAP = new HashMap<>();{
        ESCAPE_MAP.put("\\", "\\\\");
        ESCAPE_MAP.put(".",  "\\.");
    }

    private static LookupTranslator ESCAPE = new LookupTranslator(ESCAPE_MAP);

    private final static Map<CharSequence, CharSequence> UNESCAPE_MAP = new HashMap<>();{
        UNESCAPE_MAP.put("\\\\", "\\");
        UNESCAPE_MAP.put("\\.", ".");
    }

    private static LookupTranslator UNESCAPE = new LookupTranslator(UNESCAPE_MAP);

    static String escape(String text){
        return StringEscapeUtils.builder(ESCAPE).escape(text).toString();
    }

    static String unescape(String text){
        return StringEscapeUtils.builder(UNESCAPE).escape(text).toString();
    }

Upvotes: 3

Views: 233

Answers (2)

Tuco
Tuco

Reputation: 513

I think :

Instead of

private final static Map<CharSequence, CharSequence> ESCAPE_MAP = new HashMap<>();{
        ESCAPE_MAP.put("\\", "\\\\");
        ESCAPE_MAP.put(".",  "\\.");
    }

You would write :

private final static Map<CharSequence, CharSequence> ESCAPE_MAP = new HashMap<CharSequence, CharSequence>() {
        {
            put("\\", "\\\\");
            put(".", "\\.");
        }
    };

Upvotes: 0

user8097737
user8097737

Reputation:

You never fill the static Maps ESCAPE_MAP and UNESCAPE_MAP, because you forget the keyword static.

Here's the correct code

private final static Map<CharSequence, CharSequence> ESCAPE_MAP = new HashMap<>();
static {
    ESCAPE_MAP.put("\\", "\\\\");
    ESCAPE_MAP.put(".",  "\\.");
}

Upvotes: 3

Related Questions