Java: split() method with pipe special character

前端 未结 7 1373
悲&欢浪女
悲&欢浪女 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: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("[|]");
    

提交回复
热议问题