文
章
目
录
章
目
录
本教程演示了如何使用正则表达式和Java 11中的新String.strip()
API来去除Java字符串中的去除首尾空格
1.简介
字符串开头的空白字符称为前导空白字符,而字符串末尾的空白字符称为尾随空白字符。虽然我们可以使用正则表达式和其他方法来修剪空格,但自Java 11以来,建议使用strip()方法。
2.去除前导空白字符
2.1. 使用String.stripLeading()
在Java 11中添加了stripLeading()方法。它返回一个字符串,其中所有前导空白字符都被移除。
String blogName = " how to do in java ";
String strippedLeadingWhitespaces = blogName.stripLeading();
Assertions.assertEquals(strippedLeadingWhitespaces, "how to do in java ");
2.2. 使用正则表达式
这个Java示例利用了正则表达式和String的replaceAll()方法来查找所有前导空白字符。一旦我们找到了所有前导空白字符,就可以用空字符串替换它们。
String regex = "^\\s+";
String trimmedLeadingWhitespaces = blogName.replaceAll(regex, "");
Assertions.assertEquals(trimmedLeadingWhitespaces, "howtodoinjava ");
或者我们可以使用相同的正则表达式来匹配字符串开头的空白字符,并使用replaceFirst()方法替换它们。
String regex = "^\\s+";
String trimmedLeadingWhitespaces = blogName.replaceFirst(regex, "");
Assertions.assertEquals("howtodoinjava ", trimmedLeadingWhitespaces);
3.去除尾随空白字符
3.1. 使用String.stripTrailing()
stripTrailing()方法返回一个去除了所有尾随空白字符的字符串。
String blogName = " how to do in java ";
String strippedTrailingWhitespaces = blogName.stripTrailing();
Assertions.assertEquals(strippedTrailingWhitespaces , "how to do in java ");
3.2. 使用正则表达式
从字符串末尾移除空白字符的方法与前面的示例非常相似。只是正则表达式需要更改以匹配末尾的空白字符。
String regex = "\\s+$";
String trimmedTrailingWhitespaces = blogName.replaceAll(regex, "");
Assertions.assertEquals(" how to do in java", trimmedTrailingWhitespaces);
4.去除前导和尾随空白字符
4.1. 使用String.trim()
如果我们想要从字符串中删除首尾空白字符,最好的方法是使用String.trim()方法。
String blogName = " how to do in java ";
String trimmedString = blogName.trim();
Assertions.assertEquals("how to do in java", trimmedString);
4.2. 使用String.strip()
自Java 11以来,我们还可以使用strip()方法。
String blogName = " how to do in java ";
String strippedString = blogName.strip();
Assertions.assertEquals("how to do in java", strippedString);
使用上面提供的示例来从Java中的字符串中去除前导和尾随空白字符,你学会了吗?