gpt4 book ai didi

JAVA正则表达式替换所有出现的特定单词 "working weird"

转载 作者:行者123 更新时间:2023-12-01 19:28:33 26 4
gpt4 key购买 nike

有人发现我的这个正则表达式有问题吗?我想要的只是找到任何出现的 并将其替换为用户选择的单词。这个表达式只改变一些出现的情况,当它改变时,它会删除前面的空格,我猜想将它与前面的单词连接起来。而且它也不应该取代 then、there、their、they 等

private final String MY_REGEX = (" the | THE | thE | The | tHe | ThE  ");

userInput = JTxtInput.getText();
String usersChoice = JTxtUserChoice.getText();
String usersChoiceOut = (usersChoice + " ");


Pattern pattern = Pattern.compile(MY_REGEX, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(userInput);
while (matcher.find())
{
userInput = userInput.replaceAll(MY_REGEX, usersChoiceOut);
JTxtOutput.setText(userInput);
System.out.println(userInput);
}

好吧,这个新代码似乎取代了所有想要的单词,没有其他任何内容,而且也没有间距问题。

private final String MY_REGEX = ("the |THE |thE |The |tHe |ThE |THe ");
String usersChoiceOut = (usersChoice + " ");

最佳答案

问题是由于 MY_REGEX 中的空格造成的。检查以下演示:

public class Main {
public static void main(String[] args) {
String str="This is the eighth wonder of THE world! How about a new style of writing The as tHe";
// Correct way
String MY_REGEX = ("the|THE|thE|The|tHe|ThE");
System.out.println(str.replaceAll(MY_REGEX, "@@@"));
}
}

输出:

This is @@@ eighth wonder of @@@ world! How about a new style of writing @@@ as @@@

public class Main {
public static void main(String[] args) {
String str="This is the eighth wonder of THE world! How about a new style of writing The as tHe";
// Incorrect way
String MY_REGEX = ("the | THE | thE | The | tHe | ThE");
System.out.println(str.replaceAll(MY_REGEX, "@@@"));
}
}

输出:

This is @@@eighth wonder of@@@world! How about a new style of writing@@@as tHe

关于JAVA正则表达式替换所有出现的特定单词 "working weird",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com