guava中的Splitter

原创 2015年11月18日 14:58:34

来源:

 java.lang.Object 

        com.google.common.base.Splitter

字符串分割器,顾名思义根据规则将输入的字符串进行分割输出。首先来个例子:

Splitter.on(',').split("foo,bar,qux"),结果为: "foo""bar" ,"qux",结果是以迭代器的形式返回,当然,后续会说明,还会有其他的形式。
Splitter可以通过添加过滤器,从而得到自己想要的结果,例如:
默认情况下:
Splitter.on(',').split(" foo,,,  bar ,"),返回的是[" foo", "", "", " bar ", ""]。
通过添加过滤器后:
private static final Splitter MY_SPLITTER = Splitter.on(',')
       .trimResults()
       .omitEmptyStrings();
MY_SPLITTER.split("foo,,, bar ,"),返回的结果:["foo", "bar"]
这里需要注意的是:Splitter实例是immutable,通过已经包含了配置方法返回的Splitter,重新配置是无效的。
例:Splitter splitter = Splitter.on('/');  splitter.trimResults();   return splitter.split("wrong / wrong / wrong");这种是无效的。
Splitter也提供了丰富的分割器方法和过滤器方法:
static SplitterfixedLength(int length)
Returns a splitter that divides strings into pieces of the given length.
Splitterlimit(int limit)
Returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit.
SplitteromitEmptyStrings()
Returns a splitter that behaves equivalently to this splitter, but automatically omits empty strings from the results.
static Splitteron(char separator)
Returns a splitter that uses the given single-character separator.
static Splitteron(CharMatcher separatorMatcher)
Returns a splitter that considers any single character matched by the given CharMatcher to be a separator.
static Splitteron(Pattern separatorPattern)
Returns a splitter that considers any subsequence matching pattern to be a separator.
static Splitteron(String separator)
Returns a splitter that uses the given fixed string as a separator.
static SplitteronPattern(String separatorPattern)
Returns a splitter that considers any subsequence matching a given pattern (regular expression) to be a separator.
Iterable<String>split(CharSequence sequence)
Splits sequence into string components and makes them available through an Iterator, which may be lazily evaluated.
List<String>splitToList(CharSequence sequence)
Splits sequence into string components and returns them as an immutable list.
SplittertrimResults()
Returns a splitter that behaves equivalently to this splitter, but automatically removes leading and trailing whitespace from each returned substring; equivalent to trimResults(CharMatcher.WHITESPACE).
SplittertrimResults(CharMatcher trimmer)
Returns a splitter that behaves equivalently to this splitter, but removes all leading or trailing characters matching the given CharMatcher from each returned substring.
Splitter.MapSplitterwithKeyValueSeparator(char separator)
Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.
Splitter.MapSplitterwithKeyValueSeparator(Splitter keyValueSplitter)
Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified key-value splitter.
Splitter.MapSplitterwithKeyValueSeparator(String separator)
Returns a MapSplitter which splits entries based on this splitter, and splits entries into keys and values using the specified separator.
方法的详细说明:

Method Detail

  • on

    public static Splitter on(char separator)
    Returns a splitter that uses the given single-character separator. For example, Splitter.on(',').split("foo,,bar") returns an iterable containing ["foo", "", "bar"].
    Parameters:
    separator - the character to recognize as a separator
    Returns:
    a splitter, with default settings, that recognizes that separator
  • on

    public static Splitter on(CharMatcher separatorMatcher)
    Returns a splitter that considers any single character matched by the given CharMatcher to be a separator. For example, Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux") returns an iterable containing ["foo", "", "bar", "quux"].
    Parameters:
    separatorMatcher - a CharMatcher that determines whether a character is a separator
    Returns:
    a splitter, with default settings, that uses this matcher
  • on

    public static Splitter on(String separator)
    Returns a splitter that uses the given fixed string as a separator. For example, Splitter.on(", ").split("foo, bar,baz") returns an iterable containing ["foo", "bar,baz"].
    Parameters:
    separator - the literal, nonempty string to recognize as a separator
    Returns:
    a splitter, with default settings, that recognizes that separator
  • on

    @GwtIncompatible(value="java.util.regex")
    public static Splitter on(Pattern separatorPattern)
    Returns a splitter that considers any subsequence matching pattern to be a separator. For example, Splitter.on(Pattern.compile("\r?\n")).split(entireFile) splits a string into lines whether it uses DOS-style or UNIX-style line terminators.
    Parameters:
    separatorPattern - the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.
    Returns:
    a splitter, with default settings, that uses this pattern
    Throws:
    IllegalArgumentException - if separatorPattern matches the empty string
  • onPattern

    @GwtIncompatible(value="java.util.regex")
    public static Splitter onPattern(String separatorPattern)
    Returns a splitter that considers any subsequence matching a given pattern (regular expression) to be a separator. For example, Splitter.onPattern("\r?\n").split(entireFile) splits a string into lines whether it uses DOS-style or UNIX-style line terminators. This is equivalent to Splitter.on(Pattern.compile(pattern)).
    Parameters:
    separatorPattern - the pattern that determines whether a subsequence is a separator. This pattern may not match the empty string.
    Returns:
    a splitter, with default settings, that uses this pattern
    Throws:
    PatternSyntaxException - if separatorPattern is a malformed expression
    IllegalArgumentException - if separatorPattern matches the empty string
  • fixedLength

    public static Splitter fixedLength(int length)
    Returns a splitter that divides strings into pieces of the given length. For example, Splitter.fixedLength(2).split("abcde") returns an iterable containing ["ab", "cd", "e"]. The last piece can be smaller than length but will never be empty.

    Exception: for consistency with separator-based splitters, split("") does not yield an empty iterable, but an iterable containing "". This is the only case in which Iterables.size(split(input)) does not equal IntMath.divide(input.length(), length, CEILING). To avoid this behavior, use omitEmptyStrings.

    Parameters:
    length - the desired length of pieces after splitting, a positive integer
    Returns:
    a splitter, with default settings, that can split into fixed sized pieces
    Throws:
    IllegalArgumentException - if length is zero or negative
  • omitEmptyStrings

    @CheckReturnValue
    public Splitter omitEmptyStrings()
    Returns a splitter that behaves equivalently to this splitter, but automatically omits empty strings from the results. For example, Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,") returns an iterable containing only ["a", "b", "c"].

    If either trimResults option is also specified when creating a splitter, that splitter always trims results first before checking for emptiness. So, for example, Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ") returns an empty iterable.

    Note that it is ordinarily not possible for split(CharSequence) to return an empty iterable, but when using this option, it can (if the input sequence consists of nothing but separators).

    Returns:
    a splitter with the desired configuration
  • limit

    @CheckReturnValue
    public Splitter limit(int limit)
    Returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit. The limit defines the maximum number of items returned by the iterator.

    For example, Splitter.on(',').limit(3).split("a,b,c,d") returns an iterable containing ["a", "b", "c,d"]. When omitting empty strings, the omitted strings do no count. Hence, Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d") returns an iterable containing ["a", "b", "c,d". When trim is requested, all entries, including the last are trimmed. Hence Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ") results in @{code ["a", "b", "c , d"]}.

    Parameters:
    limit - the maximum number of items returns
    Returns:
    a splitter with the desired configuration
    Since:
    9.0
  • trimResults

    @CheckReturnValue
    public Splitter trimResults()
    Returns a splitter that behaves equivalently to this splitter, but automatically removes leading and trailing whitespace from each returned substring; equivalent to trimResults(CharMatcher.WHITESPACE). For example, Splitter.on(',').trimResults().split(" a, b ,c ") returns an iterable containing ["a", "b", "c"].
    Returns:
    a splitter with the desired configuration
  • trimResults

    @CheckReturnValue
    public Splitter trimResults(CharMatcher trimmer)
    Returns a splitter that behaves equivalently to this splitter, but removes all leading or trailing characters matching the given CharMatcher from each returned substring. For example, Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__") returns an iterable containing ["a ", "b_ ", "c"].
    Parameters:
    trimmer - a CharMatcher that determines whether a character should be removed from the beginning/end of a subsequence
    Returns:
    a splitter with the desired configuration
  • split

    public Iterable<Stringsplit(CharSequence sequence)
    Splits sequence into string components and makes them available through an Iterator, which may be lazily evaluated. If you want an eagerly computed List, use splitToList(CharSequence).
    Parameters:
    sequence - the sequence of characters to split
    Returns:
    an iteration over the segments split from the parameter.
  • splitToList

    @Beta
    public List<StringsplitToList(CharSequence sequence)
    Splits sequence into string components and returns them as an immutable list. If you want an Iterable which may be lazily evaluated, use split(CharSequence).
    Parameters:
    sequence - the sequence of characters to split
    Returns:
    an immutable list of the segments split from the parameter
    Since:
    15.0






 

Guava学习之Splitter

Splitter:在Guava官方的解释为:Extracts non-overlapping substrings from an input string, typically by recogni...
  • w397090770
  • w397090770
  • 2013年09月09日 23:07
  • 10015

] Guava学习笔记之Joiner ,Strings,Splitter 工具实例

[java] view plain copy Guava   一.Strings   1.Strings.padEnd方法   //padEnd普全右      ...
  • qq_26562641
  • qq_26562641
  • 2016年12月15日 09:03
  • 788

guava Splitter 与java 内置的string的split 方法的区别

java内置的会忽略空内容,guava Splitter不会忽略,也可以自由选择的忽略。 guava Splitter  可以通过splitToList方法直接将结果转成List。 /...
  • weixin_38553453
  • weixin_38553453
  • 2017年07月19日 09:54
  • 213

guava之Splitter

用于切割字符串 常用方法: 一.获得Splitter on(),onPattern(String separatorPattern) fixedLength(int length) 按...
  • idealemail
  • idealemail
  • 2016年12月24日 19:11
  • 692

【Java8】Guava——Splitter

Splitter Guava 提供了 Joiner 类用于将多个对象拼接成字符串,如果我们需要一个反向的操作,就要用到 Splitter 类。Splitter 能够将一个字符串按照指定的分隔符拆分...
  • qq_20597479
  • qq_20597479
  • 2017年04月10日 16:15
  • 500

Google Guava的splitter用法

google的guava库是个很不错的工具库,这次来学习其spliiter的用法,它是一个专门用来  分隔字符串的工具类,其中有四种用法,分别来小结  1 基本用法  import com....
  • qq_17864929
  • qq_17864929
  • 2015年08月20日 11:44
  • 703

guava的String之Splitter

guava,Splitter
  • jituotianxia2009
  • jituotianxia2009
  • 2014年05月09日 11:19
  • 2009

Guava中Splitter和Joiner的用法

字符串的分隔和连接是一个常用的操作.Guava提供了Spliiter和Joiner来帮助我们简化开发。 Splitter的用法基本用法测试代码public static void main(Strin...
  • zbw18297786698
  • zbw18297786698
  • 2017年06月14日 13:58
  • 233

Guava学习笔记之Joiner ,Strings,Splitter 工具实例

Guava 一.Strings 1.Strings.padEnd方法 //padEnd普全右 String a="12345"; String b=Strings.padEnd(a, 10, ...
  • tianyi9703
  • tianyi9703
  • 2014年12月08日 19:08
  • 1314

Google Guava 库 CharMatcher 、Joiner以及Splitter

The Guava CharMatcher CharMatcher 可以非常方便地添加到你的java工具箱中。有些人形容它:“像打了兴奋剂的StringUtils”:p 你可以使用预先设定...
  • kkgbn
  • kkgbn
  • 2014年05月09日 13:36
  • 682
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:guava中的Splitter
举报原因:
原因补充:

(最多只允许输入30个字)