Split using a bracket

后端 未结 5 1752
再見小時候
再見小時候 2021-01-04 03:34

How can I split a string using [ as the delimiter?

String line = \"blah, blah [ tweet, tweet\";

if I do

line.         


        
相关标签:
5条回答
  • 2021-01-04 04:09

    Please use "\\[" instead of "[".

    0 讨论(0)
  • 2021-01-04 04:13

    The split method operates using regular expressions. The character [ has special meaning in those; it is used to denote character classes between [ and ]. If you want to use a literal opening square bracket, use \\[ to escape it as a special character. There's two slashes because a backslash is also used as an escape character in Java String literals. It can get a little confusing typing regular expressions in Java code.

    0 讨论(0)
  • 2021-01-04 04:23

    The [ character is interpreted as a special regex character, so you have to escape it:

    line.split("\\[");

    0 讨论(0)
  • 2021-01-04 04:24

    Just escape it :

    line.split("\\[");
    

    [ is a special metacharacter in regex which needs to be escaped if not inside a character class such as in your case.

    0 讨论(0)
  • 2021-01-04 04:26

    The [ is a reserved char in regex, you need to escape it,

    line.split("\\[");
    
    0 讨论(0)
提交回复
热议问题