Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java字符串:在换行之前和之后删除所有其他空白_Java_Regex_String - Fatal编程技术网

Java字符串:在换行之前和之后删除所有其他空白

Java字符串:在换行之前和之后删除所有其他空白,java,regex,string,Java,Regex,String,我需要删除使用.trim()完成的标题和尾随空格,还需要使用使用.replaceAll(\\R+“,”)完成的单个空格替换所有换行符,但在此之前,我需要删除换行前后的所有空格(换行符除外) String toReplace = "\t\t random \t\n\r\t text \t\t"; String result = toReplace.replaceAll(Some magic, "") .rep

我需要删除使用
.trim()
完成的标题和尾随空格,还需要使用使用
.replaceAll(\\R+“,”)
完成的单个空格替换所有换行符,但在此之前,我需要删除换行前后的所有空格(换行符除外)

String toReplace = "\t\t random \t\n\r\t text \t\t";
String result = toReplace.replaceAll(Some magic, "")
                         .replaceAll("\\R+", " ")
                         .trim();

Assert.assertEquals("random text", result);

谢谢。

您可以匹配换行符周围的空格,并将其与换行符一起删除,并用空格替换:

String result=toReplace.replaceAll(“\\h*\\R+\\h*”,”).trim();
正则表达式是
\h*\R+\h*
,而
.replaceAll(“\\h*\\R+\\h*”,“”)
用一个规则空格替换以下模式序列:

  • \h*
    -零个或多个水平空白
  • \R+
    -一个或多个换行符序列
  • \h*
    -零个或多个水平空白

您能给我们看一个输入输出示例吗?