【问题标题】:String replaceAll not replacing i++;字符串 replaceAll 不替换 i++;
【发布时间】:2018-08-06 08:40:01
【问题描述】:
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");

// 想要的输出 :: newCode = "helloworld";

但这并不是用空白替换 i++。

【问题讨论】:

    标签: java string str-replace replaceall


    【解决方案1】:

    只需使用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) 将防止您在将字符串文字转换为正则表达式时出错。
    • 感谢您的建议,我已经更新了答案
    【解决方案2】:

    试试这个

     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()
    【解决方案3】:

    问题是您用于替换的字符串,即被视为正则表达式模式以跳过您必须使用如下转义序列的含义。

    String newCode = preCode.replaceAll("i\\+\\+;", "");
    

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2012-06-10
      • 2019-02-11
      • 1970-01-01
      相关资源
      最近更新 更多