【问题标题】:String replaceAll method returns wrong answerString replaceAll 方法返回错误答案
【发布时间】:2022-08-18 23:26:31
【问题描述】:

我有以下字符串:

String command = \"G()(al)\"

我在这个字符串上使用replaceAll 方法,如下所示:

command.replaceAll(\"()\", \"o\")

但它返回给我一个意想不到的字符串,即: \"oGo(o)o(oaolo)o\"

而它的输出应该是: \"Go(al)\"

谁能解释这种行为?

以及如何使用 replaceAll 方法进行转换

  1. G()(al)Go(al)
  2. G()()()(al)Gooo(al)

    标签: java string


    【解决方案1】:

    replaceAll 方法使用正则表达式,而不是纯文本。这意味着它被视为一种特殊模式,其中“()”匹配一个空组。意思是,匹配一切在你的字符串中。

    您应该改用 replace 方法,因为它使用纯文本。

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 2011-01-02
      • 2014-12-04
      • 1970-01-01
      相关资源
      最近更新 更多