问题
I want to remove all the "unpartnered" or unpaired parenthesises from a string.
exampleStr = back-pay) zyzhk1219(17) zyzhk1329 zyzhk1595(15) zyzhk1988 zyzhk2004 zyzhk2131) jswioj((testsjkldf
The expected "parenthesis balanced" string should be
back-pay zyzhk1219(17) zyzhk1329 zyzhk1595(15) zyzhk1988 zyzhk2004 zyzhk2131 jswiojtestsjkldf
I saw some ruby based solution on stackoverflow. But, couldn't find one I can use in java.
回答1:
How it might be done in pseudo-code:
initialize parenLevel = 0
for each character in string
if char is ( increment parenLevel
if char is )
if parenLevel = 0, remove bad paren
else, decrement parenLevel
next
initialize parenLevel = 0
for each character in string in reverse
if char is ) increment parenLevel
if char is (
if parenLevel = 0, remove bad paren
else, decrement parenLevel
next
How it might be implemented in practice: http://ideone.com/K3s0X
Sample result:
back-pay zyzhk1219(17) zyzhk1329 zyzhk1595(15) zyzhk1988 zyzhk2004 zyzhk2131 jswiojtestsjkldf
回答2:
This works correctly on your example string:
s = s.replaceAll("([^()]*(?:\\([^()]*\\)[^()]*)*)[()]", "$1");
Or, in more readable form:
(
[^()]* # some non-parentheses
(?:
\([^()]*\) # a matched pair of parens
[^()]* # some more non-parens
)*
)
[()] # one unpaired paren
I'm assuming you don't want to allow nested pairs of parentheses. For example, in this string:
"abc(def(ghi)jkl)mno"
...the first (
and the last )
should be removed, leaving this:
"abcdef(ghi)jklmno"
If you do want to allow nesting, there's no pure regex solution--at least, not in Java.
来源:https://stackoverflow.com/questions/9898455/using-java-remove-unbalanced-unpartnered-parenthesis