英文:
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 = "A AND (B OR (C OR D))";
String regex = "\\s+|(?<=\\()|(?=\\))";
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:
"A AND (B OR (C OR D))".split(" +| (?=\\()|(?=\\))|(?<=\\()") #=> [A, AND, (, B, OR, (, C, OR, D, ), )]
+ # splits by whitespaces
(?=\\() # splits by whitespace followed by opening brace: e.g. in " (" it would give you single "(" instead of " " and "(" (like in the next part without whitespace in the beginning)
(?=\\)) # splits by empty string followed by closing brace: e.g. "B)" => ["B", ")"]
(?<=\\)) # splits by empty string preceding by closing brace: e.g. "))"
Search for "Positive lookahead/lookbehind" in regular expressions (personally I use regex101.com).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论