Lucaciu Alex :
I am trying to split a string by a delimiter only in certain situations. To be more specific, I want to split the conditions of a split statement. I want to be able to split
"disorder == 1 or ( x < 100)"
into
"disorder == 1"
"(x < 100)"
If I use split("or")
I would get a split inside disorder
too :
"dis"
"der == 1"
"( x < 100)"
And if I try to use regex like split("[ )]or[( ]")
I would lose the parentheses from ( x < 100)
:
"disorder == 1"
"x < 100)"
I am looking for a way to split the string only if the delimiter is surrounded by space or parentheses, but I want to keep the surroundings.
Kevin Cruijssen :
You want to use Lookaheads and Lookbehinds for the spaces/parenthesis, so something like this:
String input = "disorder == 1 or( x < 100)";
String[] split = input.split("(?<=[ )])or(?=[ (])");
- The
[ )]
and[ (]
mean to look at spaces or parenthesis. This can of course be replaced with any other boundary characters, or even a literal regex boundary\\b
. - The
(?<=...)
is a positive lookbehind. So it only matchesor
when it has a space or)
in front of it, but doesn't remove them with the split. - The
(?=...)
is a lookahead. So it only matchesor
followed by a space or(
, but doesn't remove them with the split.