【问题标题】:Escaping * character in java在java中转义*字符
【发布时间】:2013-06-25 11:43:43
【问题描述】:

我正在尝试对字符串执行以下操作。

    if (combatLog.contains("//*name//*")) {
        combatLog.replaceAll("//*name//*",glad.target.name);
    }

斜线是我试图转义 *,因为没有它们就无法工作。我也尝试了一个斜线,并分别在 contains 或 replaceAll 上使用斜线。谢谢

【问题讨论】:

  • 使用backslashes转义。
  • 不要在contains()中转义星号
  • 另外,您需要将replaceAll() 的结果重新分配回字符串。字符串是不可变的,不会进行就地替换。

标签: java string escaping special-characters


【解决方案1】:

您正在使用正斜杠使用反斜杠:\ 转义字符

[编辑] 也正如 slaks 所说,您需要使用replace(),它接受字符串作为输入而不是正则表达式。

【讨论】:

    【解决方案2】:

    不要忘记字符串的不变性,并重新分配新创建的字符串。此外,如果您的 if 块不再包含任何代码,则根本不需要 if 检查。

    您有 3 个选项:

    if (combatLog.contains("*name*")) { // don't escape in contains()
        combatLog = combatLog.replaceAll("\\*name\\*", replacement);// correct escape
    }
    // another regex based solution
    if (combatLog.contains("*name*")) {
        combatLog = combatLog.replaceAll("[*]name[*]", replacement);// character class
    }
    

    或者没有正则表达式

    if (combatLog.contains("*name*")) {
        combatLog = combatLog.replace("*name*", replacement);// literal string
    }
    

    【讨论】:

      【解决方案3】:

      replaceAll()(反直觉)采用正则表达式,而不是字符串。
      要转义正则表达式的字符,您需要一个双反斜杠(加倍以从字符串文字中转义反斜杠)。

      但是,您不需要正则表达式。您应该直接调用replace(),而不需要任何转义。

      【讨论】:

        【解决方案4】:

        您正在使用正斜杠。反斜杠是转义字符。此外,除非字符串被用于正则表达式或类似的东西,否则您无需转义 *,如果您想转义,则无需转义 /

        如果战斗日志是一个字符串,它的 contains 方法只检查一个字符序列。如果要在字符串中查找*name*,只需调用combatLog.contains("*name*")

        【讨论】:

          猜你喜欢
          • 2012-08-24
          • 2012-05-18
          • 2012-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多