【问题标题】:regex match and replcae <..> characters正则表达式匹配并替换 <..> 字符
【发布时间】:2022-12-01 02:17:51
【问题描述】:

我有一个需求,匹配整个句子中的所有array&lt;object&gt;,只将&lt;&gt;替换为[]

我没有任何线索来解决这个问题。如果有人能为这个问题提供任何线索,那就太好了?

输入

Asdft array<object> tesnp array<int> 
asldhj
ashd
repl array<String>
array
asdhl
afe array<object>
endoftest

预期产出

Asdft array[object] tesnp array<int> 
asldhj
ashd
repl array<String>
array
asdhl
afe array[object]
endoftest

【问题讨论】:

  • 那么,“array<String>”呢?
  • 我编辑了问题以将相关部分放在反引号中。请注意,您在 markdown 中放入 &lt;&gt; 的内容可能会消失,除非您将它们放入代码的反引号中。
  • 在任何情况下,如果您只需要将一个文字字符串替换为另一个文字字符串,请使用 String.replace - 而不是 replaceAll
  • 您不需要正则表达式;正如@RealSkeptic 已经提到的那样,str.replace("array&lt;object&gt;", "array[object]") 就足够了。

标签: java regex regex-group regexp-replace


【解决方案1】:

您可以使用方法.replace()。此方法在字符串中搜索指定字符,并返回替换指定字符的新字符串。

在你的情况下你不需要正则表达式所以你可以写:

String replacedStr = text.replace("array<object>", "array[object]");

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 2013-01-18
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 2020-07-12
    • 2012-05-16
    相关资源
    最近更新 更多