[英]How to replace certain characters of a string
@B1AdGODG7:Devrath%Dev\¶
@B1AdGODG7:Devrath%Dev\¶
\¶
with ¶
¶
替换\¶
I tried with我试过
String comments="@B1AdGODG7:Devrath%Dev\u00B6";
comments=comments.replaceAll("\u00B6","¶");
Output : @B1AdGODG7:Devrath%Dev\¶
输出:
@B1AdGODG7:Devrath%Dev\¶
Required Output : @B1AdGODG7:Devrath%Dev¶
所需输出:
@B1AdGODG7:Devrath%Dev¶
Snapshot:快照:
\¶
is a single character, with the Unicode code point of 0xB6; \¶
是单个字符,Unicode 码位为 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("\\\\\\\¶", "¶")
.此外,反斜杠在正则表达式中是特殊的,replaceAll 使用它,因此您需要再次转义它 - 并且需要转义该转义:
replaceAll("\\\\\\\¶", "¶")
。
You could also use Pattern.quote
for that second level of escaping (the one for the regex): replaceAll(Pattern.quote("\\\¶"), "¶")
.您还可以使用
Pattern.quote
进行第二级转义(用于正则表达式): replaceAll(Pattern.quote("\\\¶"), "¶")
。
I get below example from http://techidiocy.com/replace-unicode-characters-from-java-string/ .我从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.我使用
StringEscapeUtils
提供的StringEscapeUtils
。
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.这是我遇到的最可靠的解决方案,并且已经使用了一段时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.