简体   繁体   中英

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

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:

A|B|C|The Steading\|Keir Allan\|Braco|E

My Output should look like below:

A
B
C
The Steading|Keir Allan|Braco
E

My requirement is to skip the delimiter if it is preceded by the escape sequence. I have tried the following using negative lookbehinds in String.split() :

(?<!\\)\|

But, my problem is the delimiter will be defined by the end user dynamically and it need not be always | . It can be any character on the keyboard (no restrictions). Hence, my doubt is that the above regex might fail for some of the special characters which are not allowed in regex.

I just wanted to know if this is the perfect way to do it.

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

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).

private static void splitString(String str, char escapeCharacter, char delimiter, Consumer<String> resultConsumer) {
    final StringBuilder sb = new StringBuilder();
    boolean isEscaped = false;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (c == escapeCharacter) {
            isEscaped = ! isEscaped;
            sb.append(c);
        } else if (c == delimiter) {
            if (isEscaped) {
                sb.append(c);
                isEscaped = false;
            } else {
                resultConsumer.accept(sb.toString());
                sb.setLength(0);
            }
        } else {
            isEscaped = false;
            sb.append(c);
        }
    }
    resultConsumer.accept(sb.toString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM