【问题标题】:Is it possible to use OR condition/operator in replace function?是否可以在替换功能中使用 OR 条件/运算符?
【发布时间】:2017-02-01 08:00:18
【问题描述】:

我有一个简单的 Java 字符串程序。我需要使用 replace() 函数。其中,如果它们出现在给定的字符串中,我必须在 OR 条件的帮助下替换几个单词。

e.g. String s = "I am a boy";
s = s.replace("I", "something"); //works ok
s = s.replace("I | am", "something"); //wants to do it
System.out.println(s);

我通过自己的编码以编程方式知道这是可能的,但只是想在进入最终方式之前在这里提出问题。

提前致谢。

【问题讨论】:

  • 您可以使用replaceAll 来使用正则表达式。
  • 为什么不执行两次替换?
  • 感谢 cmets。会尝试

标签: java string algorithm replace


【解决方案1】:

使用replaceAll/replaceFirst,它允许您使用正则表达式来匹配要替换的片段。

String result "I am I am a boy".replaceAll("I|am", "something");
// result = "something something something something a boy"

String result = "I am I am a boy".replaceFirst("I|am", "something");
// result = "something am I am a boy"

【讨论】:

  • 感谢您的回复。会尝试
【解决方案2】:

你可以这样做

s = s.replace(/(I|am)/g, "something");

替换功能可以搜索文本或正则表达式,对于两个或多个单词,可以使用正则表达式。这样就可以用来替换字符串中的多个单词了。

【讨论】:

  • 感谢您的回复。会尝试
  • 请编辑更多信息。不建议使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。
  • 感谢您的建议
猜你喜欢
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 2012-12-03
  • 2013-05-24
  • 1970-01-01
相关资源
最近更新 更多