Java正则表达式:移除末尾带空格的 (文件结尾处除外)
解决Java中精准替换"\r\n "(非末尾)为单个空格的问题
Got it, let's break down how to solve this exact requirement in Java. The key here is targeting only the specific \r\n (carriage return + newline + space) pattern, leaving other line breaks or indentation untouched, and skipping the instance if it's at the very end of the string.
核心实现:正则表达式替换
We can use Java's String.replaceAll() method with a carefully crafted regex to hit exactly what we need. Here's the code:
String fileText = "Sample text\r\n with a line break and space.\r\n Another example.\r\n "; // Perform the targeted replacement String processedText = fileText.replaceAll("\\r\\n (?!$)", " "); // Let's check the output: // Original end has "\r\n " which stays, others are replaced to single spaces System.out.println(processedText);
正则表达式详解
Let's break down why this regex works:
\\r\\n: Matches the literal sequence\r\n(we double up backslashes because Java requires escaping them in string literals)(?!$): This is a negative lookahead assertion. It ensures that the matched\r\nis not followed by the end of the string ($denotes the end). This is how we skip the instance at the very end of the file/text.
边界情况验证
- If your input string ends exactly with
\r\n, it won't be replaced (which is exactly what we want) - Any
\r\nthat appears in the middle of the string will be replaced with a single space - Other line break patterns (like
\nwithout\r, or\r\nwithout a trailing space) remain completely untouched
扩展:如果需要匹配"\r\n"后跟多个空格
If your use case actually involves \r\n followed by one or more spaces (not just a single space), you can adjust the regex to:
// Replace "\r\n" + one/more spaces (non-end) with single space String processedText = fileText.replaceAll("\\r\\n +(?!$)", " ");
The + quantifier matches one or more of the preceding character (space in this case).
内容的提问来源于stack exchange,提问作者Matt1713
相关产品推荐
相关产品推荐

