【发布时间】:2018-08-06 08:40:01
【问题描述】:
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// 想要的输出 :: newCode = "helloworld";
但这并不是用空白替换 i++。
【问题讨论】:
标签: java string str-replace replaceall
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// 想要的输出 :: newCode = "helloworld";
但这并不是用空白替换 i++。
【问题讨论】:
标签: java string str-replace replaceall
只需使用replace() 而不是replaceAll()
String preCode = "helloi++;world";
String newCode = preCode.replace("i++;", "");
或者如果你想要replaceAll(),应用下面的正则表达式
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i\\+\\+;", "");
注意:replace() 的第一个参数是字符序列,但replaceAll 的第一个参数是正则表达式
【讨论】:
java.util.regex.Pattern.quote(java.lang.String) 将防止您在将字符串文字转换为正则表达式时出错。
试试这个
public class Practice {
public static void main(String...args) {
String preCode = "Helloi++;world";
String newCode = preCode.replace(String.valueOf("i++;"),"");
System.out.println(newCode);
}
}
【讨论】:
String.valueOf("i++") 做什么?只需使用i++; 就足够了。你也缺少分号。
"i++;".toString()。
问题是您用于替换的字符串,即被视为正则表达式模式以跳过您必须使用如下转义序列的含义。
String newCode = preCode.replaceAll("i\\+\\+;", "");
【讨论】: