replaceAll 也替换斜线前后的完整单词

replaceAll replacing the full words before and after slash as well

我有一个需要,我需要替换一些特定的词。

例如,如果我的文字有

He needs to have java skills

我需要将其替换为

He/She needs to have java skills

我用下面的代码实现了这个

String replacedText = originalText.replaceAll("\bHe\b|\bShe\b","He/She");

但问题是当我再次执行代码时,输​​出是

He/She/He/She needs to have java skills

问题是 '\b' 正在考虑完整的单词,即使它们在斜杠之前或之后。

更新:我正在从 word/excel/html 文件中获取源代码。所以第一次它工作正常。我的意图是,如果我 运行 代码在修改后的文件上再次出现,它应该不会改变任何东西。

如何解决这个问题?

一个简单的方法可能是

String[] originalTexts = {"He needs to have java skills",
    "She needs to have java skills",
    "He/She needs to have java skills"
};
for (String original : originalTexts) {
    String replacedText = original.replaceAll("\b(She/He|He/She|He|She)\b","He/She");
    System.out.printf("original: %-32s  replacedText: %20s%n", original, replacedText);
}

开始时的一些提示:

  1. he she 可以用 s?he 重新表示(其中 s 是可选的)所以你不需要 he|she (它会让事情变得更短,同样简单)。

  2. 您也可以使用 (?i) 标志,这将使您的正则表达式不区分大小写。

现在考虑更换

  • he
  • she

还有

  • he/she
  • she/he

he/she。代表这种情况的正则表达式可以看起来像 s?he(/s?he)?

所以试试

replaceAll("(?i)\bs?he(/s?he)?\b","He/She");

我是在负前瞻和负后瞻的帮助下实现的。有了这个逻辑,我可以 运行 代码任何没有。已修改文件的次数也是如此。

private String replace(String originalText) {
    String replacedText = originalText.replaceAll(
            "\b(he(?!/)|(?<!/)she)\b", "he/she");
    replacedText = replacedText.replaceAll("\b(He(?!/)|(?<!/)She)\b",
            "He/She");
    replacedText = replacedText.replaceAll("\b(his(?!/)|(?<!/)her)\b",
            "his/her");
    replacedText = replacedText.replaceAll("\b(His(?!/)|(?<!/)Her)\b",
            "His/Her");
    replacedText = replacedText.replaceAll("\bhim(?!/)\b", "him/her");
    replacedText = replacedText.replaceAll("\bHim(?!/)\b", "Him/Her");
    return replacedText;
}

谢谢 Biffen 的想法。