String.split() *not* on regular expression?

前端 未结 8 912
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 04:31

Since String.split() works with regular expressions, this snippet:

String s = \"str?str?argh\";
s.split(\"r?\");

... yields: <

相关标签:
8条回答
  • 2020-12-03 04:42

    Escape the ?:

    s.split("r\\?");
    
    0 讨论(0)
  • 2020-12-03 04:46

    You can use

    StringUtils.split("?r")
    

    from commons-lang.

    0 讨论(0)
  • 2020-12-03 04:50

    Using directly the Pattern class, is possible to define the expression as LITERAL, and in that case, the expression will be evaluated as is (not regex expression).

    Pattern.compile(<literalExpression>, Pattern.LITERAL).split(<stringToBeSplitted>);
    

    example:

    String[] result = Pattern.compile("r?", Pattern.LITERAL).split("str?str?argh");
    

    will result:

    [st, st, argh]
    
    0 讨论(0)
  • 2020-12-03 04:54

    A general solution using just Java SE APIs is:

    String separator = ...
    s.split(Pattern.quote(separator));
    

    The quote method returns a regex that will match the argument string as a literal.

    0 讨论(0)
  • 2020-12-03 04:55

    Use Guava Splitter:

    Extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence. This separator can be specified as a single character, fixed string, regular expression or CharMatcher instance. Or, instead of using a separator at all, a splitter can extract adjacent substrings of a given fixed length.

    0 讨论(0)
  • 2020-12-03 04:55

    try

    String s = "str?str?argh";
    s.split("r\?");
    
    0 讨论(0)
提交回复
热议问题