简体   繁体   English

需要帮助用正则表达式拆分表达式

[英]Need help splitting the expression with regex

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.我希望括号作为一个单独的字符串,而不是在输出数组中与 C OR D 组合。

[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.追加,代替SPACE并在每个(和之前)之后使用.split(",")将解决我的问题。

Is there any way better way to do this by simply using the right regex in the split method ?通过在 split 方法中简单地使用正确的正则表达式,有没有更好的方法来做到这一点?

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)我使用了积极的前瞻和积极的后视,它们非常有用,所以一定要查一下(没有双关语)

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).在正则表达式中搜索“Positive lookahead/lookbehind”(我个人使用 regex101.com)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM