在文本区域中搜索和替换 java

Search and replace in textarea java

替换没有什么问题,只是在我替换完我想替换的文本区域上的所有其他字符串突然变成小写我该如何解决它

     replacebutton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            String txt = textArea.getText().toLowerCase();
            String txt2 = search.getText().toLowerCase();
            String txt3 = replace.getText();

            if (txt.contains(txt2)) {
                textArea.setText(txt.replaceAll(txt2, txt3));

            }

        }
    });

您将之前设置为小写的 txt 变量重新设置。这就是为什么在这个过程之后一切都是小写的。

您可以将不敏感替换为:

String.replaceAll("(?i)" + toReplace, Replacement);

这样使用:

public void actionPerformed(ActionEvent e) {
    String txt = textArea.getText();
    String txt2 = search.getText();
    String txt3 = replace.getText();

    if (txt.toLowerCase().contains(txt2.toLowerCase())) {
            textArea.setText(txt.replaceAll("(?i)" + txt2, txt3));

    }
}

突然小写的原因是你在 textArea.GetText() 上调用了 toLowercase。 txt 变量现在包含一个全小写的字符串。然后你调用 textArea.setText(txt...

你可以试试这个:

String txt = textArea.getText();
String txt2 = search.getText();
String txt3 = replace.getText();

if (txt.contains(txt2)) {
     textArea.setText(txt.replaceAll(txt2, txt3));
}

(但是您不会进行不区分大小写的搜索和替换..)