Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java RegEx: Split without losing token

I'm trying to write regex that will split a string when there is whitespace followed by a negative sign followed by non whitespace.

Example:

"x -y".split(regex)
returns: String[]{"x","-y"};

Currently I'm using

(?<=\\s)-(?=\\S+)

for my regex; but this returns "x","y" and eats the negative sign. is there any way to not eat the negative sign?

Thanks!

like image 671
djs22 Avatar asked Aug 15 '26 18:08

djs22


2 Answers

You may include the minus in the second group

\\s(?=-\\S+)

This gives you the desired result.

like image 145
Howard Avatar answered Aug 17 '26 08:08

Howard


Pattern:

\s(?=\-\S)

Example"

 String:  x -y z -x y z
Matches:   ^    ^

Carets point to matches

Demo:

Example Code

like image 30
Brad Christie Avatar answered Aug 17 '26 07:08

Brad Christie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!