首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在空格/not上的Java拆分

在空格/not上的Java拆分
EN

Stack Overflow用户
提问于 2020-02-20 06:23:32
回答 4查看 238关注 0票数 5

我想拆分一个字符串:"x= 2-3 y=3 z= this, that"--我会在一个或多个空白空间中拆分它,这个空格前面没有'=‘或’',意思是第一组:"x= 2-3" 2:"y=3" 3:"z= this, that" --我有一个表达式,但它唯一的好处是如果=或,后面只有一个空格。

代码语言:javascript
运行
复制
(?<![,=])\\s+ 
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-02-20 08:20:57

从另一个角度来看(向前看,而不是向后看),下面的工作会为你做吗?

代码语言:javascript
运行
复制
\\s+(?=\\S*=)
  • \\s+ -一个或多个空白字符
  • (?=\\S*=) -正前瞻,以确保后面跟着大量的非空格字符和文字等号。
票数 2
EN

Stack Overflow用户

发布于 2020-02-20 06:34:22

这一个在空白上分裂,然后是一些非空白,然后是="\\s+(?=[^=\\s]+=)"

代码语言:javascript
运行
复制
jshell> "x=   2-3   y=3 z=   this,   that".split("\\s+(?=[^=\\s]+=)")
$10 ==> String[3] { "x=   2-3", "y=3", "z=   this,   that" }
票数 1
EN

Stack Overflow用户

发布于 2020-02-20 06:30:05

这里可能很难用干净的正则分裂逻辑来表达。相反,我会在这里使用一个正式的模式匹配器,并使用regex模式:

代码语言:javascript
运行
复制
[^=\s]+\s*=.*?(?=[^=\s]+\s*=|$)

示例脚本:

代码语言:javascript
运行
复制
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));
}

这些指纹:

代码语言:javascript
运行
复制
match: x=   2-3   
match: y=3 
match: z=   this,   that

以下是regex模式的解释:

代码语言:javascript
运行
复制
[^=\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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60313993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档