如何删除^M字符java
问题: 如果字符串以 \r 结尾,则删除 \r
我从这样的事情开始
if (masterValue.endsWith(CARRIAGE_RETURN_STR)) {
masterValue = masterValue.replace(CARRIAGE_RETURN_STR, "");
}
,
public static final String CARRIAGE_RETURN_STR = (Character.toString(Constants.CARRIAGE_RETURN));
public static final char CARRIAGE_RETURN = '\r';
这对我来说似乎很尴尬。
有没有一种简单的方法可以删除 \r 字符?
然后我继续这个:
if (value.contains(CARRIAGE_RETURN_STR)) {
value = value.substring(0, value.length()-3);
//-3 因为我们从 0 (1) 开始,行以 \n (2) 结束,我们需要删除 1 char (3)
但这也看起来很尴尬。
您能提出一个更简单、更优雅的解决方案吗?
Problem:
If String ends with \r, remove \r
I started with something like this
if (masterValue.endsWith(CARRIAGE_RETURN_STR)) {
masterValue = masterValue.replace(CARRIAGE_RETURN_STR, "");
}
where
public static final String CARRIAGE_RETURN_STR = (Character.toString(Constants.CARRIAGE_RETURN));
public static final char CARRIAGE_RETURN = '\r';
This seems awkward to me.
Is there an easy way to just remove \r character?
I then moved on to this:
if (value.contains(CARRIAGE_RETURN_STR)) {
value = value.substring(0, value.length()-3);
//-3 because we start with 0 (1), line ends with \n (2) and we need to remove 1 char (3)
But this too seems awkward .
Can you suggest a easier, more elegant solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你知道,正则表达式可以支持字符串结尾锚定。 (请参阅此 Javadoc 页面< /a> 了解更多信息)
这也负责修复 \r\n --> \n,我相信。
Regexes can support end-of-string anchoring, you know. (See this Javadoc page for more information)
This also takes care of fixing \r\n --> \n, I believe.
我会这样写:
我认为为字符串“\r”创建命名常量没有意义。
顺便说一句,您的第二次尝试是不正确的,因为:
String.contains("\r")
告诉您字符串是否包含回车符,而不是它是否以回车符结尾,String.substring(int, int)
是结束字符的索引;即子字符串中不应该出现的第一个字符的位置,"\r"
的长度为1。I'd write it like this:
I see no point in creating a named constant for the String "\r".
By the way, your second attempt is incorrect because:
String.contains("\r")
tells you if the String contains a carriage return, not if it ends with a carriage return,String.substring(int, int)
is the index of the end character; i.e. the position first character that should NOT be in the substring, and"\r"
is one.