0

我正在编写应该从文本块中删除实际换行符并用字符串“\n”替换它们的代码。然后,当另一个时间读取 String 时,它应该替换换行符(换句话说,搜索所有 "\n" 并 insert \n。但是,虽然第一次转换工作正常,但它没有做后者。看起来虽然第二次替换什么也没做。为什么?

替换:

theString.replaceAll(Constants.LINE_BREAK, Constants.LINE_BREAK_DB_REPLACEMENT);

重新替换:

theString.replaceAll(Constants.LINE_BREAK_DB_REPLACEMENT, Constants.LINE_BREAK);

常数:

public static final String LINE_BREAK = "\n";
public static final String LINE_BREAK_DB_REPLACEMENT = "\\\\n";
4

2 回答 2

1

String.replaceAll(regex, replacement)中,正则表达式字符串和替换字符串都将反斜杠视为转义字符:

  • regex表示正则表达式,将反斜杠转义为\\
  • replacement是一个替换字符串,它也会转义反斜杠:

请注意,替换字符串中的反斜杠 (\) 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同;请参阅 Matcher.replaceAll。

这意味着必须在两个参数中转义反斜杠。此外,字符串常量还使用反斜杠作为转义字符,因此传递给方法的字符串常量中的反斜杠必须是双转义的(另请参阅此问题)。

这对我来说很好:

// Replace newline with "\n"
theString.replaceAll("\\n", "\\\\n");

// Replace "\n" with newline
theString.replaceAll("\\\\n","\n");

您还可以使用该Matcher.quoteReplacement()方法将替换字符串视为文字:

// Replace newline with "\n"
theString.replaceAll("\\n", Matcher.quoteReplacement("\\n"));
// Replace "\n" with newline
theString.replaceAll("\\\\n",Matcher.quoteReplacement("\n"));
于 2012-11-06T21:08:01.250 回答
1

在最后一个 replaceAll() 方法调用中不需要四个反斜杠。这对我来说似乎很好用

    String str = "abc\nefg\nhijklm";

    String newStr = str.replaceAll("\n", "\\\\n");

    String newnewStr = newStr.replaceAll("\\\\n", "\n");

输出是:

abc
efg
hijklm
abc\nefg\nhijklm
abc
efg
hijklm

我认为这是你所期望的。

于 2012-11-06T20:54:32.690 回答