Java: split() method with pipe special character

前端 未结 7 1371
悲&欢浪女
悲&欢浪女 2021-01-24 16:14

I have a String = \"Hello-new-World\". And when i use the split() method with different regex values, it acts differently.

String str = \"Hello-new-world\"
Strin         


        
相关标签:
7条回答
  • 2021-01-24 16:42

    It is a metacharacter. Escape it with a backslash, like this: "\\|"

    0 讨论(0)
  • 2021-01-24 16:43

    Pipe is special regex symbol which means OR, if you want to split by pipe then escape it in your regex:

    String[] strbuf = str.split("\\|");
    

    OR

    String[] strbuf = str.split("[|]");
    
    0 讨论(0)
  • 2021-01-24 16:44

    Presumably you're splitting on "|" in the second case - and | has a special meaning within regular expressions. If you want to split on the actual pipe character, you should escape it:

    String[] bits = whole.split(Pattern.quote("|"));
    
    0 讨论(0)
  • 2021-01-24 16:45
    str.split("|");
    

    means something different. String#split uses regex, and | is a metacharacter, so that string means: split off of the empty string or off of the empty string. That is why your string gets split on every character.

    There are a few ways of doing what you expect (use these as the string to split off of):

    "\\|"
    

    Which means to escape the metacharacter.

    "[|]"
    

    Puts the metacharacter in a character class.

    "\\Q|\\E"
    

    Puts the metacharacter in a quote

    0 讨论(0)
  • 2021-01-24 16:51

    split method takes regular expression as input. The pipe is a special character for regular expression, so if you want to use it tou need to escape the special character. Ther are multiple solutions:

    You need to escape the "pipe" character

    str.split("\\|");
    

    Or you can use the helper quote:

    str.split(Regexp.quote("|"))
    

    Or between sqares:

    str.split("[|]");
    
    0 讨论(0)
  • 2021-01-24 16:55

    The pipe has different meaning in regular expression, so if you want to use it you need to escape the special character.

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