0

Pattern.quote("/:*?"<>|#") does not seem to work when \ and " are part of the string.

The code will be receiving a sting of allowed special characters at run time, for e.g., "\/:*?"<>|#" so here \ and " need to be escaped.

What my code is required to do: Replace all characters other than alphanumeric and the allowed special characters with a default character say ~

What I have written so far:

String replacer = "~"; 

String fileName = path.replaceAll("[^\\p{IsAlphabetic}^\\p{IsDigit}\\:*?\"<>|#~]", replacer); 

This works. But how do I generalize the solution given that the allowed special characters will only be known at run time. I tried appending \\ to every allowed special character but \ and " throw errors in that case.

Grace
  • 135
  • 1
  • 12
  • Pattern.quote("/:*?"<>|#") does not seem to work when \ and " are part of the string. – Grace Dec 22 '16 at 00:18
  • 2
    `\ ` and `"` are both special characters that need to be escaped with a backslash in any string. Nothing to do with regex. – shmosel Dec 22 '16 at 00:20

0 Answers0