Java RegEx: separation without token loss

I am trying to write a regex that will split the string when there is a space followed by a negative sign followed by an insecure one.

Example:

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

I am currently using

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

for my regular expression; but it returns "x", "y" and eats a negative sign. Is there a way to not have a negative sign?

Thank!

+3
source share
4 answers

template:

\s(?=\-\S)

Example "

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

Institutions indicate matches

Demo:

Code example

+2
source

You can include minus in the second group

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

This gives the desired result.

+3
source

, . .

:

a) , , ) (\S*) (\S.*) . : "x" "-y".

split , . , .

var result = "x -y".split(" -");
if (result.length == 2) result[1] = "-" + result[1];

http://gskinner.com/RegExr/ - . , . , .

+2

, , , , - :

"x -y".split( "-" );

Remember to return again -(if necessary).

0
source

All Articles