java - Java中如何处理一行?

标签 java string split formatting line

相关行的格式为:

1:{O:{o1,Brasil,F1,G2,E1},N:{n1,Albania,D2,V2,R2,E1,A2}}

问题是,我使用 split(",") 并且我有两个字符串,我必须从每个字符串中创建一个具有所述属性的对象。如何读取每个属性并在相应的位置使用它们?

最佳答案

为此,我提供了两种特定的方法,它们对于除此特定任务之外的其他事情也很有用。

第一个方法是bracketsMaxDepth()方法,它返回特定嵌套括号的深度。支持的支架为 (), [], {}, <> 。您感兴趣的括号是大括号 ( { } )。

第二种方法是 getNestedBracketedGroups() 方法,它将解析(检索)括号字符串中嵌套括号组的内容,并在单维 (1D) 字符串数组中返回这些组内容。支持的支架为 (), [], {}, <> 。您感兴趣的括号是大括号 ( { } )。

bracketsMaxDepth() 方法由 getNestedBracketedGroups() 方法在内部使用。例如,解析出以下字符串:

String line = "1:{O:{o1,Brasil,F1,G2,E1}," + 
              "G:{g1,Germany,D2,V2,F1,G2,E1}," + 
              "N:{n1,Albania,D2,V2,R2,E1,A2}}";

我们可能会做这样的事情(我添加了一个额外的生物进行测试):

String line = "1:{O:{o1,Brasil,F1,G2,E1},G:{g1,Germany,D2,V2,F1,G2,E1},N:{n1,Albania,D2,V2,R2,E1,A2}}";
line = line.trim();

// Get player Number
String player = line.substring(0, line.indexOf(":"));
// Is the player a string representation of a integer number?
if (!player.matches("\\d+")) { 
    // Nope...exit
    return; // or whatever exit mechanism you need to use.
}
int playerNumber = Integer.parseInt(player);

// Get Player's Creatures...
String[] playerCreatures = getNestedBracketedGroups(line, 1, "{}", 
                            true)[0].split(",(?![^\\{\\}]*\\})");

// Display creatures data
System.out.println("Creatures for Player #" + playerNumber);
for (int i = 0; i < playerCreatures.length; i++) {
    String creat = playerCreatures[i];
    int creatureNumber = i + 1;
    String creatureType= creat.substring(0, creat.indexOf(":"));
    // Get creature Attributes
    String[] creatureAttributes = creat.substring((creatureType + ":").length() + 1, 
                                  creat.length() - 1).split("\\s{0,},\\s{0,}");

    System.out.println("\tCreature #" + creatureNumber);
    System.out.println("\t\tCreature Type: " + creatureType);
    for (int j = 0; j < creatureAttributes.length; j++) {
        System.out.println("\t\t\tAttribute #" + (j + 1) + ": " + creatureAttributes[j]);
    }
}

控制台窗口的解析输出如下所示:

Creatures for Player #1
    Creature #1
        Creature Type: O
            Attribute #1: o1
            Attribute #2: Brasil
            Attribute #3: F1
            Attribute #4: G2
            Attribute #5: E1
    Creature #2
        Creature Type: G
            Attribute #1: g1
            Attribute #2: Germany
            Attribute #3: D2
            Attribute #4: V2
            Attribute #5: F1
            Attribute #6: G2
            Attribute #7: E1
    Creature #3
        Creature Type: N
            Attribute #1: n1
            Attribute #2: Albania
            Attribute #3: D2
            Attribute #4: V2
            Attribute #5: R2
            Attribute #6: E1
            Attribute #7: A2
<小时/>

The bracketsMaxDepth() method:

/**
 * This method takes a string and returns the maximum depth of nested
 * brackets. The bracket type to check the depth for is supplied within the
 * bracketType parameter.<br><br>
 *
 * @param bracketedString (String) The string to process.<br>
 *
 * @param bracketType     (String - Default is "()") Either a open bracket,
 *                        or a close bracket, or both open and closed
 *                        brackets can be supplied (no white-spaces). This
 *                        method will process any <b>one</b> of 4 different
 *                        bracket types and they are as follows:<pre>
 *
 *      ()      Parentheses       (Default)
 *      {}      Curly Braces
 *      []      Square Brackets
 *      &lt;&gt;      Chevron Brackets</pre>
 *
 * @return (Integer) The maximum depth of the supplied bracket type. 0 is
 *         returned if there are no brackets of the type supplied within the
 *         supplied string. -1 is returned if there is an unbalance within
 *         the supplied string of the supplied bracket type. For every open
 *         bracket there must be a close bracket and visa versa.
 */
public static int bracketsMaxDepth(String bracketedString, String... bracketType) {
    char open = '(';    // Default
    char close = ')';   // Default
    if (bracketType.length > 0) {
        String bType = Character.toString(bracketType[0].charAt(0));
        switch (bType) {
            case "(":
            case ")":
                open = '(';
                close = ')';
                break;
            case "{":
            case "}":
                open = '{';
                close = '}';
                break;
            case "[":
            case "]":
                open = '[';
                close = ']';
                break;
            case "<":
            case ">":
                open = '<';
                close = '>';
                break;
            default:
                throw new IllegalArgumentException("\nbracketsMaxDepth() Method Error!\n"
                        + "Unknown bracket type supplied (" + bType + ")!\n");
        }
    }

    int current_max = 0; // current count
    int max = 0;    // overall maximum count
    int n = bracketedString.length();
    char[] c = bracketedString.toCharArray();

    // Traverse the input string
    for (int i = 0; i < n; i++) {
        if (c[i] == open) {
            current_max++;
            // update max if required
            if (current_max > max) {

                max = current_max;
            }
        }
        else if (c[i] == close) {
            if (current_max > 0) {
                current_max--;
            }
            else {
                return -1;
            }
        }
    }

    // finally check for unbalanced string
    if (current_max != 0) {
        return -1;
    }

    return max;
}
<小时/>

The getNestedBracketedGroups() method:

/**
 * This method will parse out (retrieve) the contents of nested brackets
 * groups within a bracketed string and return those group contents within a
 * 1D String Array. The best way to see how this works is by examples. Let's
 * say we have the following bracketed string:
 * <pre>
 *
 *      String a = "1(2(3)(4))(5(6)(7))";</pre><br>
 * <p>
 * In the above string we can see that there are two instances of level 1
 * bracketed groups which in each level 1 group nest two more level 2
 * bracketed groups:
 * <pre>
 *
 *       Level 1         Level 2
 *      (2(3)(4))        (3) (4)
 *
 * ==================================
 *
 *       Level 1         Level 2
 *       (5(6)(7))       (6) (7)</pre><br>
 * <p>
 * Bracketed groups: <b>(2(3)(4))</b> and <b>(5(6)(7))</b> are both
 * considered to be at nest level 1 (level 1 is the outer most level). They
 * are both individual groups because they both have their own set of outer
 * brackets. Within each level 1 group we have two sets of level 2 bracketed
 * groups (4 level 2 groups altogether) which consist of: <b>(3)</b> &
 * <b>(4)</b> and <b>(6)</b> & <b>
 * (7)</b>.<br><br>
 * <p>
 * This method also utilizes the TokenJar's StringUtils.BracketsMaxDepth()
 * method.
 *
 * @param bracketedString     (String) The string which contains bracketed
 *                            content to parse.<br>
 *
 * @param desiredDepth        (Integer) Default is 0 (full depth). The
 *                            nested depth to retrieve bracketed content
 *                            from.<br> If the bracket depth supplied is
 *                            deeper than what is contained within the
 *                            supplied input string then an <b>IllegalArgu-
 *                            mentException</b> is thrown explaining as
 *                            such.
 *
 * @param bracketType         (String) You must supply the bracket type to
 *                            process. This can be done by supplying either
 *                            a single open or close bracket or both open
 *                            and close brackets, for example, any one of
 *                            the following are all acceptable entries if
 *                            parentheses are required:<pre>
 *
 *      "("     ")"     "()"    ")("</pre><br>
 *
 * Any one of four (4) bracket types can be supplied. The allowable Bracket
 * Types are:
 * <pre>
 *
 *      ()      Parentheses
 *      {}      Curly Braces
 *      []      Square Brackets
 *      &lt;&gt;      Chevron Brackets</pre>
 *
 * @param removeOuterBrackets (Optional - Boolean - Default is false) By
 *                            default the outer brackets for each found
 *                            group are also attached to the returned
 *                            results. If true is supplied to this optional
 *                            parameter then the outer brackets are removed
 *                            from the returned group results.<br>
 *
 * @return (1D String Array) The determined nested groups desired.<br>
 *
 * @throws IllegalArgumentException if a depth is supplied greater than the
 *                                  available bracketed depth contained
 *                                  within the supplied input string. This
 *                                  exception is also thrown if it is found
 *                                  that the supplied Bracket Type is
 *                                  unbalanced (open and closed braces are
 *                                  not properly paired) within the supplied
 *                                  input string.
 */
public static String[] getNestedBracketedGroups(String bracketedString, int desiredDepth,
        String bracketType, boolean... removeOuterBrackets) {
    boolean removeOuter = false;
    if (removeOuterBrackets.length > 0) {
        removeOuter = removeOuterBrackets[0];
    }

    int d = bracketsMaxDepth(bracketedString, bracketType);
    if (desiredDepth == 0) {
        //Default for this method is 0 (full depth).
        desiredDepth = 1;
    }
    if (d == -1) {
        // Throw Exception...
        throw new IllegalArgumentException("\n\ngetNestedBracketedGroups() Method Error!\n"
                + "Brackets mismatch in supplied string!\n");
    }
    else if (d < desiredDepth) {
        // Throw Another Exception...
        throw new IllegalArgumentException("\n\ngetNestedBracketedGroups() Method Error!\n"
                + "Invalid Depth Supplied! Brackets within the supplied string go to a\n"
                + "maximum depth of (" + d + ") and therefore can not go to the supplied "
                + "depth\nof (" + desiredDepth + "). Change the desired depth.\n");
    }

    char open = '(';    // Default
    char close = ')';   // Default
    String bType = Character.toString(bracketType.charAt(0));
    switch (bType) {
        case "(":
        case ")":
            open = '(';
            close = ')';
            break;
        case "{":
        case "}":
            open = '{';
            close = '}';
            break;
        case "[":
        case "]":
            open = '[';
            close = ']';
            break;
        case "<":
        case ">":
            open = '<';
            close = '>';
            break;
        default:
            throw new IllegalArgumentException("\ngetNestedBracketedGroups() Method Error!\n"
                    + "Unknown bracket type supplied (" + bType + ")!\n");
    }

    List<String> list = new ArrayList<>();
    int n = bracketedString.length();
    char[] c = bracketedString.toCharArray();
    int depth = 0;
    String strg = "";
    for (int i = 0; i < n; i++) {
        if (c[i] == open) {
            depth++;
        }
        if ((depth >= desiredDepth)) {
            if (c[i] == close) {
                depth--;
            }
            strg += Character.toString(c[i]);

            if (depth < desiredDepth) {
                strg = strg.trim();
                if (removeOuter) {
                    if (strg.startsWith(Character.toString(open))) {
                        strg = strg.substring(1);
                    }
                    if (strg.endsWith(Character.toString(close))) {
                        strg = strg.substring(0,
                                strg.lastIndexOf(Character.toString(close)));
                    }
                }
                list.add(strg);
                strg = "";
            }

            continue;
        }
        if (c[i] == close) {
            depth--;
        }
        if (!strg.equals("")) {
            strg = strg.trim();
            if (removeOuter) {
                if (strg.startsWith(Character.toString(open))) {
                    strg = strg.substring(1);
                }
                if (strg.endsWith(Character.toString(close))) {
                    strg = strg.substring(0,
                            strg.lastIndexOf(Character.toString(close)));
                }
            }
            list.add(strg);
            strg = "";
        }
    }
    if (!strg.equals("")) {
        strg = strg.trim();
        if (removeOuter) {
            if (strg.startsWith(Character.toString(open))) {
                strg = strg.substring(1);
            }
            if (strg.endsWith(Character.toString(close))) {
                strg = strg.substring(0,
                        strg.lastIndexOf(Character.toString(close)));
            }
        }
        list.add(strg); // + Character.toString(close));
    }
    //  (red(blue))grey((orange)green)
    return list.toArray(new String[list.size()]);
}

关于java - Java中如何处理一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61032064/

相关文章:

java - 如何正确创建多维数组的集合

java - 如何将值传递到树集中用户定义的比较函数中

java - keystore 类型 : which one to use?

java - 更改类变量并保存更改以供将来的程序运行?

php - 如何从多行中检索值作为单个字符串

无法清除字符数组

.net - 如何从 .NET 中的字符串中删除变音符号(重音符号)?

regex - 如何在 perl 中将字符串的字母和数字分开?

javascript - JS react : replacing regex with component in a string

python - 如何在 Python 中将电子邮件地址/密码字符串一分为二?