Java - Splitting String based on multiple delimiters

后端 未结 4 1429
广开言路
广开言路 2020-12-06 06:44

I essentially want to split up a string based on the sentences, therefore (for the sake of what I\'m doing), whenever there is a !, ., ?

相关标签:
4条回答
  • 2020-12-06 06:44

    You can use the String.split(String regex) method with parameter "[!.?:;]".

    0 讨论(0)
  • 2020-12-06 06:49

    The argument of String.split is a regex, so you can create a pattern that matches any of those characters.

    s.split("[.!:;?]");
    
    0 讨论(0)
  • 2020-12-06 06:59

    String.split takes a regex to split on, so you can simply:

    mystring.split("[!.?:;]");
    
    0 讨论(0)
  • 2020-12-06 07:11

    Guava's Splitter is a bit more predictable than String.split().

    Iterable<String> results = Splitter.on(CharMatcher.anyOf("!.?:;"))
       .trimResults() // only if you need it
       .omitEmptyStrings() // only if you need it
       .split(string);
    

    and then you can use Iterables.toArray or Lists.newArrayList to wrap the output results how you like.

    0 讨论(0)
提交回复
热议问题