[英]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(",")
將解決我的問題。
通過在 split 方法中簡單地使用正確的正則表達式,有沒有更好的方法來做到這一點?
這個怎么樣:
String input = "A AND (B OR (C OR D))";
String regex = "\\s+|(?<=\\()|(?=\\))";
String[] tokens = input.split(regex);
返回:
{A, AND, (, B, OR, (, C, OR, D, ), )}
正則表達式拆分為
我使用了積極的前瞻和積極的后視,它們非常有用,所以一定要查一下(沒有雙關語)
我希望這會有所幫助:
"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. "))"
在正則表達式中搜索“Positive lookahead/lookbehind”(我個人使用 regex101.com)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.