Groovy/Java split string on parentheses “(”

前端 未结 5 1891
小鲜肉
小鲜肉 2020-12-09 03:00

I am trying to perform a split similar the following:

println \"Hello World(1)\".split(\"W\");

Output:

[Hello , orld(1)]


        
相关标签:
5条回答
  • 2020-12-09 03:29

    Since split just accept regex, you have to pass to it as an escaped character. For this, you must append a backslash in front of it

    \(
    

    But above has a compile error because it is parsed as a valid escaped character such as:

    \t Tab
    \n New Line or Line Feed
    \r Carriage Return
    

    So, you must pass a non meaning character (E.g. parenthesis) with 2 backslashes:

    \\(
    

    Finally:

    println "Hello World(1)".split("\\(");
    

    OR you can also do all things by java builtin function of class Pattern named quote:

    println "Hello World(1)".split(Pattern.quote("("));
    
    0 讨论(0)
  • 2020-12-09 03:30
    println "Hello World(1)".split("\\(");
    
    0 讨论(0)
  • 2020-12-09 03:46

    you have to escape the bracket character properly

    println "Hello World(1)".split("\\(")
    
    0 讨论(0)
  • 2020-12-09 03:51

    The split method takes a regular expression pattern.

    If you want to split on "just a regular string" you can use Pattern.quote to quote the string first:

    println "Hello World(1)".split(Pattern.quote("("))
    
    0 讨论(0)
  • 2020-12-09 03:52

    You can also use a single escape when using groovy native regex syntax:

    assert "Hello World(1)".split(/\(/) == ["Hello World", "1)"]
    
    0 讨论(0)
提交回复
热议问题