Handling delimiter with escape characters in Java String.split() method

后端 未结 2 1315
无人及你
无人及你 2021-02-04 02:51

I have searched the web for my query, but didn\'t get the answer which fits my requirement exactly. I have my string like below:



        
相关标签:
2条回答
  • 2021-02-04 03:24

    You can use Pattern.quote():

    String regex = "(?<!\\\\)" + Pattern.quote(delim);
    

    Using your example:

    String delim = "|";
    String regex = "(?<!\\\\)" + Pattern.quote(delim);
    
    for (String s : "A|B|C|The Steading\\|Keir Allan\\|Braco|E".split(regex))
        System.out.println(s);
    
    A
    B
    C
    The Steading\|Keir Allan\|Braco
    E
    

    You can extend this to use a custom escape sequence as well:

    String delim = "|";
    String esc = "+";
    String regex = "(?<!" + Pattern.quote(esc) + ")" + Pattern.quote(delim);
    
    for (String s : "A|B|C|The Steading+|Keir Allan+|Braco|E".split(regex))
        System.out.println(s);
    
    A
    B
    C
    The Steading+|Keir Allan+|Braco
    E
    
    0 讨论(0)
  • 2021-02-04 03:27

    I know this is an old thread, but the lookbehind solution has an issue, that it doesn't allow escaping of the escape character (the split would not occur on A|B|C|The Steading\\|Keir Allan\|Braco|E)).

    The positive matching solution in thread Regex and escaped and unescaped delimiter works better (with modification using Pattern.quote() if the delimiter is dynamic).

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