Im trying to search all the special characters in a string and escape them. The Input String must be failsafe so I need to escape the characters.
The example String looks for example like this : "Foo Bar "Gone Wild "- <br>Ted Talk</br> "
To secure that the String still looks the same it needs to be something like this afterwards "Foo Bar \"Gone Wild \" \- \<br\>Ted Talk \<\/br\>"
I came up with this solution:
final String[] metaCharacters = {"\\", "^", "$", "{", "}", "[", "]", "(", ")", ".", "*", "+", "?", "|", "<", ">", "-", "&", "#"};
String outputString = "";
for (int characterIndex = 0; characterIndex < metaCharacters.length; characterIndex++) {
if (inputString.contains(metaCharacters[characterIndex])) {
outputString = inputString.replace(metaCharacters[characterIndex], "\\" + metaCharacters[characterIndex]);
}
}
But I'm not very happy with that. Its written in Java.