Splitting a Java String by the pipe symbol using split(“|”)

前端 未结 7 873
生来不讨喜
生来不讨喜 2020-11-21 23:32

The Java official documentation states:

The string \"boo:and:foo\", for example, yields the following results with these expressions Regex Result :

相关标签:
7条回答
  • 2020-11-22 00:08

    You can also use .split("[|]").

    (I used this instead of .split("\\|"), which didn't work for me.)

    0 讨论(0)
  • 2020-11-22 00:11
    test.split("\\|",999);
    

    Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

    But test.split("\\|"); will return different length strings arrays for the same examples.

    use reference: link

    0 讨论(0)
  • 2020-11-22 00:22

    the split() method takes a regular expression as an argument

    0 讨论(0)
  • 2020-11-22 00:23

    You need

    test.split("\\|");
    

    split uses regular expression and in regex | is a metacharacter representing the OR operator. You need to escape that character using \ (written in String as "\\" since \ is also a metacharacter in String literals and require another \ to escape it).

    You can also use

    test.split(Pattern.quote("|"));
    

    and let Pattern.quote create the escaped version of the regex representing |.

    0 讨论(0)
  • 2020-11-22 00:23

    You could also use the apache library and do this:

    StringUtils.split(test, "|");
    
    0 讨论(0)
  • 2020-11-22 00:27

    Use proper escaping: string.split("\\|")

    Or, in Java 5+, use the helper Pattern.quote() which has been created for exactly this purpose:

    string.split(Pattern.quote("|"))
    

    which works with arbitrary input strings. Very useful when you need to quote / escape user input.

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