需要帮忙使用正则表达式分割这个表达式。

huangapple go评论66阅读模式
英文:

Need help splitting the expression with regex

问题

我有一个类似这样的表达式。

A AND (B OR (C OR D))

我希望将括号作为一个单独的字符串,而不是与C OR D结合在输出数组中。

[A, AND, (, B, OR, (, C, OR, D, ), )]

在每个之后和每个之前,以及在SPACE的位置添加“,”,然后使用.split("","),可以解决我的问题。

是否有更好的方法,仅通过在分割方法中使用正确的正则表达式来实现这一点?

英文:

I have an expression like this.

A AND (B OR (C OR D))

I want the parentheses as a separate string and not combined with C OR D in the output array.

[A, AND, (, B, OR, (, C, OR, D, ), )]

Appending , in place of SPACE and after every ( and before every ) and then using .split(",") would solve my problem.

Is there any way better way to do this by simply using the right regex in the split method ?

答案1

得分: 2

String input = "A AND (B OR (C OR D))";
String regex = "\\s+|(?<=\\()|(?=\\))";
String[] tokens = input.split(regex);

返回:

{A, AND, (, B, OR, (, C, OR, D, ), )}

解释:

这个正则表达式根据以下规则进行分割:

  • 一个或多个空格
  • 左括号后面的任何内容
  • 右括号前面的任何内容

我使用了正向后瞻(positive lookaheads)和正向先行断言(positive lookbehinds),它们非常有用,请务必查阅相关资料(纯属巧合)。

英文:

How about this:

String input = &quot;A AND (B OR (C OR D))&quot;;
String regex = &quot;\\s+|(?&lt;=\\()|(?=\\))&quot;;
String[] tokens = input.split(regex);

Which returns:

{A, AND, (, B, OR, (, C, OR, D, ), )}

Explanation:

The regex splits by

  • One or more spaces
  • Anything followed by a parenthesis
  • Anything preceded by a parenthesis

I used positive lookaheads and positive lookbehinds, which are INCREDIBLY useful, so do look them up (no pun intended)

答案2

得分: 0

我希望这能帮助到您:

"A AND (B OR (C OR D))".split(" +| (?=\()|(?=\))|(?<=\()") #=> [A, AND, (, B, OR, (, C, OR, D, ), )]
 + # 通过空格进行分割
 (?=\() # 通过空格后跟开括号进行分割:例如在 " (" 中,它将给出单个 "(",而不是 " " 和 "("(就像下一部分在开头没有空格的情况下)
(?=\)) # 通过空字符串后跟闭括号进行分割:例如 "B)" => ["B", ")"]
(?<=\)) # 通过空字符串前面有闭括号进行分割:例如 "))"

在正则表达式中搜索 "正向前瞻/后顾"(Positive lookahead/lookbehind),您可以使用 regex101.com 进行搜索。

英文:

I hope this would help:

&quot;A AND (B OR (C OR D))&quot;.split(&quot; +| (?=\\()|(?=\\))|(?&lt;=\\()&quot;) #=&gt; [A, AND, (, B, OR, (, C, OR, D, ), )]
 + # splits by whitespaces
 (?=\\() # splits by whitespace followed by opening brace: e.g. in &quot; (&quot; it would give you single &quot;(&quot; instead of &quot; &quot; and &quot;(&quot; (like in the next part without whitespace in the beginning)
(?=\\)) # splits by empty string followed by closing brace: e.g. &quot;B)&quot; =&gt; [&quot;B&quot;, &quot;)&quot;]
(?&lt;=\\)) # splits by empty string preceding by closing brace: e.g. &quot;))&quot;

Search for "Positive lookahead/lookbehind" in regular expressions (personally I use regex101.com).

huangapple
  • 本文由 发表于 2020年9月18日 19:31:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63954952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定