[英]How to remove a carriage return from a string
String s ="SSR/DANGEROUS GOODS AS PER ATTACHED SHIPPERS
/DECLARATION 1 PACKAGE
NFY
/ACME CONSOLIDATORS"
Java's String.replaceAll
in fact takes a regular expression. Java的String.replaceAll
实际上带有一个正则表达式。 You could remove all newlines with: 您可以使用以下命令删除所有换行符:
s = s.replaceAll("\\n", "");
s = s.replaceAll("\\r", "");
But this will remove all newlines. 但这将删除所有换行符。
Note the double \\
's: so that the string that is passed to the regular expression parser is \\n
. 请注意双\\
::以便传递给正则表达式解析器的字符串为\\n
。
You can also do this, which is smarter: 您也可以这样做,这更聪明:
s = s.replaceAll("\\s{2,}", " ");
This would remove all sequences of 2 or more whitespaces, replacing them with a single space. 这将删除2个或更多空格的所有序列,并用单个空格替换它们。 Since newlines are also whitespaces, it should do the trick for you. 由于换行符也是空格,因此应该为您解决问题。
试试这个代码:
s = s.replaceAll( "PACKAGE\\s*NFY", "PACKAGE NFY" );
s = s.replaceAll("[\\n\\r]", "");
Have you tried a replace function? 您是否尝试过替换功能? Something in the lines of: 符合以下条件的东西:
youString.Replace("\r", "")
string = string.replace(/\s{2,}/g, ' ');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.