how to split a string with a condition in java

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 matches or 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 matches or followed by a space or (, but doesn't remove them with the split.

Try it online.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116844&siteId=1