简体   繁体   English

Java RegEx:拆分而不丢失令牌

[英]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. 但这会返回“x”,“y”并吃掉负号。 is there any way to not eat the negative sign? 有没有办法不吃负号?

Thanks! 谢谢!

You may include the minus in the second group 您可以在第二组中包含减号

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

This gives you the desired result. 这为您提供了理想的结果。

You are capturing the minus sign which is used to split. 您正在捕获用于拆分的减号。 Therefore it is removed. 因此它被删除。

Two possible solutions: 两种可能的解决方

a) add it to the second match because it has to be there otherwise the split wouldn't return this result b) try (\\S*) (\\S.*) instead and do a match. a)将它添加到第二个匹配,因为它必须在那里,否则拆分不会返回此结果b)尝试(\\S*) (\\S.*)而是进行匹配。 This will return two results, "x" and "-y". 这将返回两个结果,“x”和“-y”。

If the split function is such a simple one consider using the string split function. 如果split函数是如此简单,可以考虑使用字符串split函数。 Its much faster than regex. 它比正则表达快得多。

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

http://gskinner.com/RegExr/ is a nice site to check your regular expressions. http://gskinner.com/RegExr/是一个检查正则表达式的好网站。 If you compare your regex with Howards you will see the difference. 如果你将你的正则表达式与Howards进行比较,你会看到差异。 If you take mine and do a match, too. 如果你拿我的并做一场比赛。

Pattern: 图案:

\s(?=\-\S)

Example" 例”

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

Carets point to matches Carets指向匹配

Demo: 演示:

Example Code 示例代码

If there will always be a space between the values you want to split, consider using something like: 如果要分割的值之间总是有空格,请考虑使用以下内容:

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

Just remember to put the - back in (if that is required). 只记得把-放回去(如果需要的话)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM