Table of contents
(1) Problem description
At work this week, I met a requirement. The general requirement function is: maintain a connector in the configuration table, here is configured with [\r\n] newline character, when the front end obtains data display, use the configuration table 【\r\n】Line breaks are spliced and displayed. It seems to be a simple requirement. After finishing, I will return the spliced string to the front end. A strange thing happened. The front end does not display a new line, but [ \r\n】The content is displayed as it is.
So, I started to debug the code, looked at the code for a long time, and found that [\r\n] in the string after I spliced is an ordinary character, not a newline character. [\r\n] is replaced with a newline character [\r\n], and the replaceAll() method is used for replacement processing. The code is as follows:
String str = "[1111111\r\n22222]";
// 替换普通的字符 \r\n 为换行符 \r\n
str = str.replaceAll("\r\n", "\r\n");
After a while of operation, it is found that it does not take effect? ? ? ? Ordinary \r\n was not replaced with a newline character. I didn't want to understand why. I searched on Baidu and finally found the reason. The solution is as follows.
(2) Solutions
In the above code using the replaceAll() method to replace [\r\n], since the replaceAll() method uses a regular expression for parsing, and the [\] backslash needs to be transferred in the regular expression, if If there is no transfer, then a [\] backslash is used as an escape character. To represent a normal [\] backslash, you need to express [\\] like this, using two backslashes to represent, the first backslash The slash is an escape for the second backslash.
There is another problem. Although [\] has been transferred, the combination of [\] and [r] is the carriage return character in the regular expression, so [\r] needs to be escaped to make it change If it is an ordinary character, then write it like this: [\\\\r], four backslashes plus a lowercase [r] means an ordinary [\r] character.
String str = "[1111111\r\n22222]";
// 替换普通的字符 \r\n 为换行符 \r\n
// TODO 注意:这里一定要使用四个斜杠
str = str.replaceAll("\\\\r\\\\\n", "\r\n");
So far, the problem of dealing with [\r\n] newline characters in the replaceAll() method has been solved.