How to know Which character was replaced while using regex
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. i.e.
" -> \"
' -> \'.
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.
精彩评论