String string = "Tĥïŝ ĩš â fůňķŷ Šťŕĭńġs not cool \"oops" ;
string = string.replaceAll("[^a-zA-Z0-9 ]+", ... );
The problem is that I want to append to non alphanumeric non whitespace characters an escape character. ie
" -> \"
' -> \'.
So what exactly should be a second argument in the replaceAll
method? Or is there any other cool way (I don't want to hardcode)
If this is Java (I added the relevant tag), then you could do
String resultString = subjectString.replaceAll("[\\W\\S]", "\\\\$0");
which will replace any non-alnum/non-space character with its escaped counterpart.
Note that the regex is making no attempt to detect whether a character is already escaped. You should also be aware that \W
in Java is not locale-aware, so it will match Unicode letters, too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.