[英]Replace special character from String
I have a String
str =\\'abc\\'
which I am printing. 我正在打印一个
String
str =\\'abc\\'
。 Its printing like \\'abc'\\
instead of 'abc'
. 它的打印像
\\'abc'\\
而不是'abc'
。
I have tried this option: str.replaceAll("\\\\", "");
我已经尝试过此选项:
str.replaceAll("\\\\", "");
but its giving me java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 但它给了我java.util.regex.PatternSyntaxException:索引1附近发生意外的内部错误
Can anyone help resolve this issue. 任何人都可以帮助解决此问题。
Why are you using regex you can do: 为什么使用正则表达式可以执行以下操作:
str = str.replace("\\", "");
If you have to use regex then you need to use: 如果必须使用正则表达式,则需要使用:
str = str.replace("\\\\", "");
regex needs double escaping in Java since String and regex engine bot needs escaping. 由于String和regex引擎bot需要转义,因此regex在Java中需要两次转义。
Your method: 您的方法:
private static String getNewString(String str) {
str.replaceAll("\\\\", "");
System.out.println("The updated String : "+str);
return str;
}
will return the initial string, since string is immutable. 将返回初始字符串,因为字符串是不可变的。 str.replaceAll will leave str as it is and it will generate a new string.
str.replaceAll将按原样保留str并将生成一个新字符串。
Change your test case to this: 将您的测试用例更改为此:
public static void main(String ...string) {
String str = "\\'a\\'";
System.out.println("The original String : "+str);
str = getNewString(str);
}
private static String getNewString(String str) {
String rez = str.replaceAll("\\\\", "");
System.out.println("The updated String : "+rez);
return rez;
}
i think you mean : 我想你的意思是:
public class Abc { 公共课程Abc {
public static void main(String[] args) {
String str ="\'abc\'";
System.out.println(str);
}
} }
output : 'abc' 输出:'abc'
it is coming correct for me. 对我来说这是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.