Java 将全部替换为正则表达式中的新行



我想将文本" 1n2 "("1"换行符和"2")替换为例如" abcd "。我一直在寻找很多解决方案,但我找不到。

下面是我的代码

String REGEX = "1n2";
Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
Matcher m = p.matcher(text);
String newText = m.replaceAll("abcd");

[编辑]我想补充一点,文本变量是从文件中读取的:

String text = new Scanner(new File("...")).useDelimiter("\A").next();

尝试将正则表达式更改为

String REGEX = "1\n2";

所以它逃脱了n

例:

public static void main(String[] args) {
    String REGEX = "1n2";
    Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
    Matcher m = p.matcher("test1n2test");
    String newText = m.replaceAll("abcd");
    System.out.println(newText);
}
操作

/操作:

testabcdtest

甚至只是

String newText = "test1n2test".replaceAll("1n2", "abcd");

O/P

testabcdtest

为什么要为此使用正则表达式?只需使用

String newText = text.replace("1n2", "abcd");

试试这个

String str="Your String"
str=str.replace("1n2","abc");

最新更新