[英]Escape characters displayed in TextView
In an Android app I'm making, I construct a TextView
programmatically and pass a String
to setText
. 在我正在制作的Android应用中,我以编程方式构造TextView
并将String
传递给setText
。 The String I'm passing is obtained from another source, and it contains escape characters. 我传递的字符串是从另一个来源获得的,它包含转义字符。 Here's an example String: 这是一个示例字符串:
AxnZt_35\/435\/46\/34
The \\/
should in fact be just /
. 实际上, \\/
应该只是/
。 But the TextView
displays the whole thing exactly as in the above example. 但是TextView
完全按照上面的示例显示整个内容。
The code I'm using to construct the TextView
: 我用来构造TextView
的代码:
TextView textView = new TextView(context);
textView.setText(text);
textView.setTextColor(color);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setTextSize(14);
So my question is, how can I not display the extra \\
? 所以我的问题是,我怎么不显示多余的\\
? I just want the above example displayed as: 我只希望上面的示例显示为:
AxnZt_35/435/46/34
Thanks. 谢谢。
EDIT 编辑
The String I provided above is just an example. 我上面提供的字符串只是一个示例。 There might be other characters in the String. 字符串中可能还有其他字符。 For example, the character /
or \\
by itself is perfectly valid. 例如,字符/
或\\
本身是完全有效的。 The problem is that /
is displayed as \\/
. 问题是/
显示为\\/
。
The answer from @Numan1617 is close, but for escape characters and replaceAll()
, you have to escape them twice. @ Numan1617的答案很接近,但是对于转义字符和replaceAll()
,您必须对它们进行两次转义。
So, the correct code in this case would be: 因此,在这种情况下,正确的代码将是:
String str = "AxnZt_35\\/435\\/46\\/34";
System.out.println(str); //prints AxnZt_35\/435\/46\/34
String s2 = str.replaceAll("\\\\/", "/");
System.out.println(s2); //prints AxnZt_35/435/46/34
您必须使用Strings replaceAll方法设置文本之前,替换所有\\的出现:
textView.setText(text.replaceAll("\\", ""));
Run this as plain Java 作为普通Java运行
public class Klass{
public static void main(String[] args) {
System.out.println(new String("\\/"));
System.out.println(new String("\\/").replaceAll("/", ""));
System.out.println(new String("\\/").replaceAll("\\/", ""));
System.out.println(new String("\\/").replaceAll("\\\\/", ""));
}
}
The regex for \\ is "\\\\": in regex one pair of \\ is equal to one \\ in the new String() \\的正则表达式为“ \\\\”:在正则表达式中,一对\\等于新String()中的一个\\
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.