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