0

What regexp to use to remove the escape characters in the received data.

Examples:

dd\.mm\.yyyy -> dd.mm.yyyy
d\-mm\-yy -> d-mm-yyyy
m\\d\\yyyy -> m\d\yyyy

Tests:

assertEquals("m\\d\\yyyy", removeEscapeChars("m\\\\d\\\\yyyy"));
assertEquals("dd-mm-yyyy", removeEscapeChars("dd\\-mm\\-yyyy"));
assertEquals("dd.mm.yyyy", removeEscapeChars("dd\\.mm\\.yyyy"));
Ilya
  • 720
  • 6
  • 14
  • is your second example a typo or why would get the dashes suddenly turn to points? – OH GOD SPIDERS Mar 29 '19 at 09:45
  • 2
    Possible duplicate of [How to unescape a Java string literal in Java?](https://stackoverflow.com/questions/3537706/how-to-unescape-a-java-string-literal-in-java) – Ivo Mar 29 '19 at 09:50

1 Answers1

3

It looks like you want to replace \x with x. To do that you can use

str = str.replaceAll("\\\\(.)", "$1");
  • "\\\\" as regex represents single \ created by "\\" in string literals
  • . can represent any character (except line separators, but that shouldn't be a problem based on your example)
  • (.) will place it in "capturing-group" which will be indexed as 1
  • $1 in replacement formula, allows us to use current match of group 1 (character matched by ., so it would be character which was escaped with \).
Pshemo
  • 122,468
  • 25
  • 185
  • 269