如何用特殊字符拆分字符串并忽略括号内的所有内容?

我想用“/”分割字符串并忽略外括号内的“/”。

示例输入字符串:

"Apple 001/(Orange (002/003) ABC)/Mango 003 )/( ASDJ/(Watermelon )004)/Apple 002 ASND/(Mango)"

字符串数组中的预期输出:

["Apple 001", "(Orange (002/003) ABC)", "Mango 003 )/( ASDJ", "(Watermelon )004)", "Apple 002 ASND", "(Mango)"]

这是我的正则表达式:

\/(?=(?:[^\(\)]*\([^\(\)]*\))*[^\(\)]*$)

但它只能支持这样的简单字符串:

"Apple 001/(Orange 002/003 ABC)/Mango 003 ASDJ/(Watermelon 004)/Apple 002 ASND/(Mango)"

如果有内括号,则结果不正确。


倚天杖
浏览 171回答 1
1回答

qq_花开花谢_0

这是一个可以实现您需求的解析器示例:public static List<String> splitter(String input) {&nbsp; &nbsp; int nestingLevel=0;&nbsp; &nbsp; StringBuilder currentToken=new StringBuilder();&nbsp; &nbsp; List<String> result = new ArrayList<>();&nbsp; &nbsp; for (char c: input.toCharArray()) {&nbsp; &nbsp; &nbsp; &nbsp; if (nestingLevel==0 && c == '/') { // the character is a separator !&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(currentToken.toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentToken=new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (c == '(') { nestingLevel++; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (c == ')' && nestingLevel > 0) { nestingLevel--; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentToken.append(c);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; result.add(currentToken.toString());&nbsp; &nbsp; return result;}你可以在这里试试。请注意,它不会导致您发布的预期输出,但我不确定您遵循什么算法来获得这样的结果。特别是我已经确保没有“负嵌套级别”,所以对于初学者来说,/in"Mango 003 )/( ASDJ"被认为在括号之外并被解析为分隔符。无论如何,我确信您可以比正则表达式答案更容易地调整我的答案,我的答案的全部意义在于表明编写解析器来处理此类问题通常比费心尝试制作正则表达式更现实。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java