且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-27 21:01:56

下面是解析器的示例,可以满足您的需求:

Here's a sample of a parser that would implement your need :

public static List<String> splitter(String input) {
    int nestingLevel=0;
    StringBuilder currentToken=new StringBuilder();
    List<String> result = new ArrayList<>();
    for (char c: input.toCharArray()) {
        if (nestingLevel==0 && c == '/') { // the character is a separator !
            result.add(currentToken.toString());
            currentToken=new StringBuilder();
        } else {
            if (c == '(') { nestingLevel++; }
            else if (c == ')' && nestingLevel > 0) { nestingLevel--; }

            currentToken.append(c);
        }
    }
    result.add(currentToken.toString());
    return result;
}

您可以在此处尝试.

请注意,这不会导致您发布预期的输出,但是我不确定要遵循哪种算法才能获得这样的结果.特别是,我确保没有负嵌套级别",因此对于初学者来说,在"Mango 003)/(ASDJ" 中的/被认为在括号之外,并且解析为分隔符.

Note that it doesn't lead to the expected output you posted, but I'm not sure what algorithm you were following to obtain such result. In particular I've made sure there's no "negative nesting level", so for starters the / in "Mango 003 )/( ASDJ" is considered outside of parenthesis and is parsed as a separator.

无论如何,我敢肯定,与正则表达式答案相比,您可以更轻松地调整我的答案,我的答案的全部目的是表明,编写解析器来处理此类问题通常比打扰要更实际.正则表达式.

Anyway I'm sure you can tweak my answer much more easily than you would a regex answer, the whole point of my answer being to show that writing a parser to handle such problems is often more realistic than to bother trying to craft a regex.