美文网首页Google Guava学习笔记guava
Basic Guava Utilities-CharMatche

Basic Guava Utilities-CharMatche

作者: Viking_Den | 来源:发表于2016-09-05 21:07 被阅读66次

    CharMatcher提供操作字符以及字符串的功能,如下面的代码:

    CharMatcher.BREAKING_WHITESPACE.replaceFrom(stringWithLinebreaks,' ');
    

    如果需要将多个连续的tab键和空格键合并为单个空格键,可以使用下面的代码:

     @Test
     public void testRemoveWhiteSpace(){
       String tabsAndSpaces = "String   with   spaces and    tabs";
       String expected = "String with spaces and tabs";
       String scrubbed = CharMatcher.WHITESPACE.collapseFrom(tabsAndSpaces,' ');
       assertThat(scrubbed,is(expected));
     }
    

    上面的例子有个问题,如果空格键或者tab键在字符串的开始处则也会合并为单个空格,这显然不是我们想要的,CharMatcher提供了trimAndCollapseFrom方法来处理上述的情况:

    @Test
     public void testTrimRemoveWhiteSpace(){
       String tabsAndSpaces = "    String    with   spaces   and     tabs";
       String expected = "String with spaces and tabs";
       String scrubbed = CharMatcher.WHITESPACE.trimAndCollapseFrom(tabsAndSpaces,' ');
       assertThat(scrubbed,is(expected));
     }
    

    CharMatcher还有一个最广泛有用的功能就是,能组合多种字符的匹配模式,如下面的代码片段:

    CharMatcher cm = CharMatcher.JAVA_DIGIT.or(CharMatcher.WHITESPACE);
    

    上面的匹配器不仅会匹配数字而且还会匹配空格键。

    相关文章

      网友评论

        本文标题:Basic Guava Utilities-CharMatche

        本文链接:https://www.haomeiwen.com/subject/cfarettx.html