Java正则表达式:以空格分割/不以...开头

5
我想要拆分字符串:"x= 2-3 y=3 z= this, that",我希望通过一个或多个空格进行拆分,但这些空格不应该紧接在'='或','之后。 意思是第一组为:"x= 2-3", 第二组为:"y=3", 第三组为:"z= this, that"。 我有一个表达式可以实现,但只适用于'='或','后只有一个空格的情况。
(?<![,=])\\s+ 
4个回答

2
倒过来思考(向前看而不是向后看),以下内容是否适合您的需求?
\\s+(?=\\S*=)
  • \\s+ - 表示一个或多个空白字符
  • (?=\\S*=) - 正向预查,确保后面跟着尽可能多的非空白字符和一个等号。

谢谢,完美 - Daniel Jeney

1
这个正则表达式会在白空格后面跟着一些非空白字符再加上 = 进行分割:"\\s+(?=[^=\\s]+=)"
jshell> "x=   2-3   y=3 z=   this,   that".split("\\s+(?=[^=\\s]+=)")
$10 ==> String[3] { "x=   2-3", "y=3", "z=   this,   that" }

0

在这里编写清晰的正则表达式分割逻辑可能会很困难。相反,我会使用一个正式的模式匹配器,并使用以下正则表达式模式:

[^=\s]+\s*=.*?(?=[^=\s]+\s*=|$)

示例脚本:

String input = "x=   2-3   y=3 z=   this,   that";
String pattern = "[^=\\s]+\\s*=.*?(?=[^=\\s]+\\s*=|$)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("match: " + m.group(0));
}

这将打印:

match: x=   2-3   
match: y=3 
match: z=   this,   that

这是正则表达式模式的解释:

[^=\s]+           match a variable
\s*               followed by optional whitespace
=                 match =
.*?               consume everything, until seeing the nearest
(?=
    [^=\s]+\s*=   the next variable followed by =
    |             or
    $             or the end of the input (covers the z= case)
)

0

如果你想使用负向先行断言,你可以断定左侧是一个模式,例如匹配 x= 2-3 并匹配后面的空格字符。

使用 否定字符类 [^\\h=,] 来匹配除了列出的字符以外的任何字符。

(?<=[^\\h=,]=\\h{0,100}[^\\h=,]{1,100})\\h+

正则表达式演示 | Java演示

正则表达式演示使用了不同的引擎,仅用于显示匹配结果。

在Java中,您需要使用双重转义,并且可以使用\h来匹配1个或多个水平空格字符,而不是\s

Java不支持回顾后发无限宽度,但支持有限宽度。

例如:

String s = "x=   2-3   y=3 z=   this,   that";
String regex = "(?<=[^\\h=,]=\\h{0,100}[^\\h=,]{1,100})\\h+";
String parts[] = s.split(regex);

for (String part : parts)
    System.out.println(part);

输出

x=   2-3
y=3
z=   this,   that

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接