【问题标题】:Java can't replace "{" with replaceAll method [duplicate]Java不能用replaceAll方法替换“{”[重复]
【发布时间】:2019-01-13 09:00:11
【问题描述】:

我们正在使用 String 的 replaceAll 方法,我们不能替换任何字符串中的 {。 我们的例子:

试过了:

"some { string".replaceAll("{", "other string");

错误如下:

java.util.regex.PatternSyntaxException: 发生非法重复

欢迎任何想法!也许有解决方法?!

【问题讨论】:

  • 你需要逃脱它\{应该做的工作
  • 您可能需要转义字符 {。试试.replaceAll("\\{", "other string");
  • 除非您尝试使用正则表达式,否则您应该使用replace,而不是replaceAll

标签: java string methods replaceall


【解决方案1】:

使用 replaceAll 需要 regular expression (regex)

尝试使用replace方法而不是replaceAll

"some { string".replace("{", "other string");

或使用\\转义正则表达式中的特殊字符

"some { string".replaceAll("\\{", "other string");

【讨论】:

    【解决方案2】:

    像这样尝试replace()

    "some { string".replace("{", "other string");
    

    或使用replaceAll 与以下正则表达式格式

    "some { string".replaceAll("\\{", "your string to replace");
    

    注意:replace() 的第一个参数是字符序列,但replaceAll 的第一个参数是正则表达式

    【讨论】:

    • replace 替换所有出现,而不仅仅是第一个。见docs.oracle.com/javase/6/docs/api/java/lang/…@Korashen @Navneet Krishna
    • @Korashen .replace.replaceAll 都替换所有出现。.replaceAll 与正则表达式一起使用,.replace 没有。说实话,名称约定简直糟透了。.replaceAll.replaceAllWithRegex 或者类似的东西会更有意义。旁注:还有一个.replaceFirst 方法,就像.replaceAll 一样只接受正则表达式,但只会替换第一次出现。
    • 天哪,你是对的。搞混了...删除了我的评论,因为它是错误的。当时我想到的是什么......
    【解决方案3】:

    您需要转义{,因为它在regex 中具有特殊含义。使用:

    String s = "some { string".replaceAll("\\{", "other string");
    

    【讨论】:

      【解决方案4】:

      您需要转义字符 "{" 。

      试试这个:

      "some { string".replaceAll("\\{", "other string");
      

      【讨论】:

        【解决方案5】:

        { 是正则表达式引擎的指示符,表明您将要启动重复指示符,例如 {2,4} 表示“前一个标记的 2 到 4 倍”。

        但是{f是非法的,因为后面必须跟一个数字,所以会抛出异常。

        你可以这样做

        "some { string".replaceAll("\\{", "other string");
        

        【讨论】:

          【解决方案6】:

          你必须使用转义字符\\:

          "some { string".replaceAll("\\{", "other string");
          

          字符{ 保留在正则表达式中,这就是为什么你必须转义它以匹配文字。或者,您可以使用replace 仅考虑CharSequence,而不是正则表达式。

          【讨论】:

            【解决方案7】:
            1. 替换: "xxx".replace("{","xxx")
            2. 全部替换: "xxx".replace("\{","xxx")

            Difference between String replace() and replaceAll()

            【讨论】:

              猜你喜欢
              • 2016-06-20
              • 2011-04-06
              • 2014-10-08
              • 1970-01-01
              • 2015-10-25
              • 2020-11-06
              • 1970-01-01
              • 1970-01-01
              • 2012-09-21
              相关资源
              最近更新 更多