使用正则表达式交换两个特定单词



我有一个这样的文本:

男孩女孩循环用于退出男孩女孩左-右

我想使用regex交换boygirl(注意:boy/girl无序出现。(所以我写这个:

String str = "boy girl loop for get out boy girl left right";
String regex = "(\bgirl\b)|(\bboy\b)";
System.out.println(str.replaceAll(regex, "$2$1"));

但它不起作用你能告诉我为什么并给出正确的解决方案吗

您可以使用;回调";在使用Matcher#replaceAll:的替换中

String str = "boy girl loop for get out boy girl left right";
Matcher m = Pattern.compile("\b(girl)\b|\b(boy)\b").matcher(str);
System.out.println( m.replaceAll(r -> r.group(2) != null ? "girl" : "boy") );
// => girl boy loop for get out girl boy left right

在线观看Java演示。

这里,b(girl)b|b(boy)b将整个单词girl匹配到组1,并且将boy匹配到组2。

r -> r.group(2) != null ? "girl" : "boy"替换检查组2是否匹配,如果不匹配,则替换为girl,否则为boy

还有一个";用字典代替";方法:

String[] find = {"girl", "boy"};
String[] replace = {"boy", "girl"};

Map<String, String> dictionary = new HashMap<String, String>();
for (int i = 0; i < find.length; i++) {
dictionary.put(find[i], replace[i]);
}

String str = "boy girl loop for get out boy girl left right";
Matcher m = Pattern.compile("\b(?:" + String.join("|", find) + ")\b").matcher(str);
System.out.println( m.replaceAll(r -> dictionary.get(r.group())) );
// => girl boy loop for get out girl boy left right 

请参阅此Java演示。

您可以尝试以下代码。我只是用一个";temp";regex介于两者之间,以便替换两个单词。

String str = "boy girl loop for get out boy girl left right";
String regexGirl = "(girl)";
String regexBoy = "(boy)";
System.out.println(str.replaceAll(regexGirl, "temp").replaceAll(regexBoy, "girl").replaceAll("temp", "boy"));

最新更新