简体   繁体   中英

How to replace certain characters of a string

  • I have a string @B1AdGODG7:Devrath%Dev\¶
  • I want to replace with

I tried with

String comments="@B1AdGODG7:Devrath%Dev\u00B6";
comments=comments.replaceAll("\u00B6","¶");
  • Output : @B1AdGODG7:Devrath%Dev\¶

  • Required Output : @B1AdGODG7:Devrath%Dev¶


  • ReplaceAll is not working
  • How to make the required output

Snapshot:

在此处输入图片说明

is a single character, with the Unicode code point of 0xB6; writing is literally the same as writing ¶.

So, you need to escape the backslash: \\\\ . Furthermore, backslashes are special in regular expressions, which replaceAll uses, so you need to escape it again -- and that escape needs to be escaped: replaceAll("\\\\\\\¶", "¶") .

You could also use Pattern.quote for that second level of escaping (the one for the regex): replaceAll(Pattern.quote("\\\¶"), "¶") .

I get below example from http://techidiocy.com/replace-unicode-characters-from-java-string/ . I think it is work for u

public static StringBuffer removeUTFCharacters(String data){
Pattern p = Pattern.compile("\\\\u(\\p{XDigit}{4})");
Matcher m = p.matcher(data);
StringBuffer buf = new StringBuffer(data.length());
while (m.find()) {
String ch = String.valueOf((char) Integer.parseInt(m.group(1), 16));
m.appendReplacement(buf, Matcher.quoteReplacement(ch));
}
m.appendTail(buf);
return buf;
}

I use StringEscapeUtils provided by apache.

You can use it by adding following dependency:

implementation 'org.apache.commons:commons-text:1.4'

Code Sample:

String comments="@B1AdGODG7:Devrath%Dev\u00B6";
Log.d("output", StringEscapeUtils.unescapeJava(comments));

Output:

D/output: @B1AdGODG7:Devrath%Dev¶

This is the most reliable solution i have come across for this problem and have been using it for a while.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM