我想拆分一个字符串:"x= 2-3 y=3 z= this, that"
--我会在一个或多个空白空间中拆分它,这个空格前面没有'=‘或’',意思是第一组:"x= 2-3"
2:"y=3"
3:"z= this, that"
--我有一个表达式,但它唯一的好处是如果=或,后面只有一个空格。
(?<![,=])\\s+
发布于 2020-02-20 08:20:57
从另一个角度来看(向前看,而不是向后看),下面的工作会为你做吗?
\\s+(?=\\S*=)
\\s+
-一个或多个空白字符(?=\\S*=)
-正前瞻,以确保后面跟着大量的非空格字符和文字等号。发布于 2020-02-20 06:34:22
这一个在空白上分裂,然后是一些非空白,然后是=
:"\\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" }
发布于 2020-02-20 06:30:05
这里可能很难用干净的正则分裂逻辑来表达。相反,我会在这里使用一个正式的模式匹配器,并使用regex模式:
[^=\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
以下是regex模式的解释:
[^=\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)
)
https://stackoverflow.com/questions/60313993
复制相似问题