我尝试使用 StringUtils.stripEnd
去除字符串中的尾随字符,并注意到如果我尝试从 "FOO_FOO 中去除
,这将返回一个空字符串。例如,"_FOO"
"
import org.apache.commons.lang3.StringUtils;
public class StripTest {
public static void printStripped(String s1, String suffix){
String result = StringUtils.stripEnd(s1, suffix);
System.out.println(String.format("Stripping '%s' from %s --> %s", suffix, s1, result));
}
public static void main(String[] args) {
printStripped("FOO.BAR", ".BAR");
printStripped("BAR.BAR", ".BAR");
printStripped("FOO_BAR", "_BAR");
printStripped("BAR_BAR", "_BAR");
printStripped("FOO-BAR", "-BAR");
printStripped("BAR-BAR", "-BAR");
}
}
哪些输出
Stripping '.BAR' from FOO.BAR --> FOO
Stripping '.BAR' from BAR.BAR -->
Stripping '_BAR' from FOO_BAR --> FOO
Stripping '_BAR' from BAR_BAR -->
Stripping '-BAR' from FOO-BAR --> FOO
Stripping '-BAR' from BAR-BAR -->
有人可以解释一下这种行为吗?没看到examples from docs本案的。使用 Java 7。
最佳答案
查看 StringUtils Javadoc 中的文档和示例:
Strips any of a set of characters from the end of a String.
A null input String returns null. An empty string ("") input returns the empty string.
If the stripChars String is null, whitespace is stripped as defined by Character.isWhitespace(char).
StringUtils.stripEnd(null, *) = null
StringUtils.stripEnd("", *) = ""
StringUtils.stripEnd("abc", "") = "abc"
StringUtils.stripEnd("abc", null) = "abc"
StringUtils.stripEnd(" abc", null) = " abc"
StringUtils.stripEnd("abc ", null) = "abc"
StringUtils.stripEnd(" abc ", null) = " abc"
StringUtils.stripEnd(" abcyx", "xyz") = " abc"
StringUtils.stripEnd("120.00", ".0") = "12"
这不是您想要的,因为它会从末尾的任意位置删除字符集。我相信您正在寻找 removeEnd(...)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null. An empty ("") source string will return the empty string. A null search string will return the source string.
StringUtils.removeEnd(null, *) = null
StringUtils.removeEnd("", *) = ""
StringUtils.removeEnd(*, null) = *
StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "") = "abc"
removeEnd(...)
操作的不是一组字符,而是一个子字符串,这就是您要提取的内容。
关于Java StringUtils.stripEnd 带有句点、连字符或下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837780/