Bwi*_*ire 5 java regex split string-split
我想在逗号(,)上用java分割字符串,但只要逗号(,)在某个括号之间,就不应该拆分.
例如,字符串:
"life, would, (last , if ), all"
Run Code Online (Sandbox Code Playgroud)
应该产量:
-life
-would
-(last , if )
-all
Run Code Online (Sandbox Code Playgroud)
我用的时候:
String text = "life, would, (last , if ), all"
text.split(",");
Run Code Online (Sandbox Code Playgroud)
我最终将整个文本划分为(最后,如果)我可以看到拆分需要一个正则表达式,但我似乎无法想到如何使它完成工作.
你可以使用这种模式 - (不适用于嵌套的括号)
,(?![^()]*\))
Run Code Online (Sandbox Code Playgroud)
, # ","
(?! # Negative Look-Ahead
[^()] # Character not in [()] Character Class
* # (zero or more)(greedy)
\ #
) # End of Negative Look-Ahead
)
Run Code Online (Sandbox Code Playgroud)