带有句点,连字符或下划线的Java StringUtils.stripEnd

时间:2017-01-24 19:53:58

标签: java string apache

我尝试使用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。

1 个答案:

答案 0 :(得分:2)

查看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(...)不是一组字符,而是一个子字符串,这是你想要提取的字符串。