What is the proper way of inserting a pipe into a Java Pattern expression?

后端 未结 4 918
情话喂你
情话喂你 2020-12-29 03:32

What is the proper way of inserting a pipe into a Java Pattern expression?

I actually want to use a pipe as a delimiter and not the or operator.

I.E:

相关标签:
4条回答
  • 2020-12-29 03:47

    Escape it with \\:

    "hello|world".split("\\|");
    
    0 讨论(0)
  • 2020-12-29 03:52
    "hello|world".split("\\\\|"); --> {"hello", "world"}
    

    First set of "\\" only yields the \ as the delimiter. Therefore 2 sets are needed to escape the pipe.

    0 讨论(0)
  • 2020-12-29 04:05

    in Java 1.5+:

    "hello|world".split(Pattern.quote("|"));
    
    0 讨论(0)
  • 2020-12-29 04:05

    I have this problem a lot (encoding a regex into a Java String), so I have bookmarked the regex tool at fileformat.info; it has a nifty function where it will show you the Java String representation of a regex after you test it.

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