如何在字符串中去除多余的空格和换行符,但至少保留每个空行组中的一个空行。
例如,将以下输入:
"This is
a string.
Something."
为了
"This is
a string.
Something."
我正在使用
.trim()
来清除字符串开头和结尾的空格,但我找不到可以删除字符串中多余的空格和换行符的方法。我想只保留一个空格和一个换行符。如何在字符串中去除多余的空格和换行符,但至少保留每个空行组中的一个空行。
例如,将以下输入:
"This is
a string.
Something."
为了
"This is
a string.
Something."
.trim()
来清除字符串开头和结尾的空格,但我找不到可以删除字符串中多余的空格和换行符的方法。我想只保留一个空格和一个换行符。一行代码解决多个空格/换行符问题,但至少保留一个空白行:
str = str.replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
每一行都被修剪了。
这是一些测试代码:
String str = " This is\r\n " +
"\r\n" +
" \r\n " +
" \r \n \n " +
"\r\n" +
" a string. ";
str = str.trim().replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
System.out.println(str);
输出:
This is
a string.
text.replaceAll("\\n\\s*\\n", "\\n").replaceAll("[ \\t\\x0B\\f]+", " ").trim());
首先,它将两个换行符之间仅有的空格替换为单个换行符,然后忽略换行符将其他任何空格缩减为一个空格。
public String keepOneWS(String str) {
Pattern p = Pattern.compile("(\\s+)");
Matcher m = p.matcher(str);
Pattern pBlank = Pattern.compile("[ \t]+");
String newLineReplacement = System.getProperty("line.separator") +
System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
while (m.find()) {
if(pBlank.matcher(m.group(1)).matches()) {
m.appendReplacement(sb, " ");
} else {
m.appendReplacement(sb, newLineReplacement);
}
}
m.appendTail(sb);
return sb.toString().trim();
}
public void testKeepOneWS() {
String str = " This \t is\r\n " +
"\r\n" +
" \r\n " +
" \r \n \t \n " +
"\r\n" +
" a \t string. \t ";
String expected = "This is" + System.getProperty("line.separator")+
System.getProperty("line.separator") + "a string.";
String actual = keepOneWS(str);
System.out.println("'" + actual + "'");
assertEquals(expected, actual);
}
'This is
a string.'
+
表示至少一个或更多,你可以使用{2,}
表示至少两个或更多。 - A4L
' a string.'
- A4L