从Java String的末尾删除行尾字符 [英] Remove end of line characters from end of Java String
问题描述
我有一个字符串,我只想使用Java从字符串的最末端删除行尾字符
I have a string which I'd like to remove the end of line characters from the very end of the string only using Java
"foo\r\nbar\r\nhello\r\nworld\r\n"
我想成为
"foo\r\nbar\r\nhello\r\nworld"
(这个问题类似于,但不是问题 593671 )
(This question is similar to, but not the same as question 593671)
推荐答案
你可以使用 s = s.replaceAll([\\\\ n] + +,);
。这会修剪字符串末尾的 \ r
和 \ n
字符
正则表达式解释如下:
-
[\\\\ n ]
是一个包含\ r
和\ n
的字符类 -
+
是一次或多次重复 -
$
是字符串结束锚点
[\r\n]
is a character class containing\r
and\n
+
is one-or-more repetition of$
is the end-of-string anchor
- regular-expressions.info/Anchors, Character Class, Repetition
您还可以使用 String.trim()
从开头和任何空白字符>结束字符串:
You can also use String.trim()
to trim any whitespace characters from the beginning and end of the string:
s = s.trim();
如果你需要检查 String
只包含空格字符,你可以检查它是否 trim()之后的nofollow noreferrer> isEmpty()
:
If you need to check if a String
contains nothing but whitespace characters, you can check if it isEmpty()
after trim()
:
if (s.trim().isEmpty()) {
//...
}
或者你也可以看看它是否 匹配(\\\\ *)
,即空白字符的零个或多个。请注意,在Java中,正则表达式匹配
尝试匹配整个字符串。在可以匹配子字符串的风格中,您需要锚定模式,因此它是 ^ \s * $
。
Alternatively you can also see if it matches("\\s*")
, i.e. zero-or-more of whitespace characters. Note that in Java, the regex matches
tries to match the whole string. In flavors that can match a substring, you need to anchor the pattern, so it's ^\s*$
.
- regex, check if a line is blank or not
- how to replace 2 or more spaces with single space in string and delete leading spaces only
这篇关于从Java String的末尾删除行尾字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!