开发者

How to know Which character was replaced while using regex

开发者 https://www.devze.com 2023-03-12 10:22 出处:网络
String string = \"Tĥïŝ ĩš â fůňķŷ Šťŕĭńġs not cool \\\"oops\" ; string = string.replaceAll(\"[^a-zA-Z0-9 ]+\", ... );
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号