Search code examples
javastringreplaceall

Why doesn't .replaceAll() work correctly?


I have two strings.

String wef = "83 Cool 4555"; // From server
String wef2 = "83 Cool 4555"; // From server

wef = wef.replaceAll("/[^A-Za-z0-9- ]/", "").replaceAll("\\s+", " ");
wef2 = wef2.replaceAll("\\s+", " ");

wef.contains(wef2); // Returns FALSE.

If I print out the values of wef and wef2, then compare them in a diff checker, I get this from the diff checker:

https://i.sstatic.net/aiCgX.png

There's something wrong with the spaces, even though I replace all \\s+ with a regular space. Why doesn't .replaceAll() work correctly?


Solution

  • Get rid of the leading and trailing slashes, unless you are actually looking for non-alphanumeric(-hyphenic-spacic) characters surrounded by slashes:

    wef.replaceAll("[^A-Za-z0-9- ]", "").replaceAll("\\s+", " ")