REGEX 匹配器不替换反斜杠

REGEX Matcher not replacing backslah

Matcher 中的函数 appendReplacement(StringBuffer sb, String replacement) 忽略带有双反斜杠的转义字符。我想将两行替换为由 \N 分隔的一行。这是我的代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class Test {

    public static void main(String[] args) {
        String str = "Lorem ipsum dolor sit amet,\n"
                + "consectetur adipiscing elit\n"
                + "\n"
                + "sed do eiusmod tempor incididunt ut\n"
                + "labore et dolore magna aliqua\n";
        StringBuffer sb = new StringBuffer();
        Pattern p = Pattern.compile("(.+)\n(.+)\n");
        Matcher m = p.matcher(str);
        while(m.find()) {
            String xyz = m.group(1) + "\N" + m.group(2);
            System.out.println(xyz);
            m.appendReplacement(sb, xyz);
        }                    
        m.appendTail(sb);
        System.out.println("\n" + sb);
    }

}  

输出:

痛苦本身很重要,\N减肥精英会成功 但与此同时,它们发生了 ut\Nlabore 并且带来了巨大的痛苦

事实是疼痛本身很重要 但是在那个时候发生了一些巨大的劳动和痛苦

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

您正在 xyzString 对象中插入 \N。 append 函数会将反斜杠字符替换为替换字符,就像将其放入 String 文字中一样。因此,要通过 append 函数得到一个 \N,你需要对它进行两次转义:\\N