如何在Java中处理一行?

huangapple go评论145阅读模式
英文:

How to process a line in Java?

问题

以下是翻译好的部分:

问题中所涉及的行的格式如下:

1:{O:{o1,巴西,F1,G2,E1},N:{n1,阿尔巴尼亚,D2,V2,R2,E1,A2}}

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

英文:

The format of line in question is:

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

The thing is, I use the split(",") and I have two strings and from each of them I have to create an object with said attributes. How can I read each one of the attributes and use them in its corresponding place?

答案1

得分: 0

以下是您提供的内容的翻译部分:


为了实现这一点,我提供了两种特定的方法,除了这个特定的任务,它们还可以用于其他事情。

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

第二个方法是 getNestedBracketedGroups() 方法,它将解析括号字符串中嵌套括号组的内容(提取),并将这些组的内容返回到单维字符串数组中。支持的括号类型为 (), [], {}, <>。您感兴趣的是花括号( { } )。

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

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();
    
// 获取玩家编号
String player = line.substring(0, line.indexOf(":"));
// 玩家是一个整数表示的字符串吗?
if (!player.matches("\\d+")) { 
    // 不是的话...退出
    return; // 或者使用您需要的其他退出机制。
}
int playerNumber = Integer.parseInt(player);
    
// 获取玩家的生物...
String[] playerCreatures = getNestedBracketedGroups(line, 1, "{}", 
                            true)[0].split(",(?![^\\{\\}]*\\})");
    
// 显示生物数据
System.out.println("玩家 #" + playerNumber);
for (int i = 0; i < playerCreatures.length; i++) {
    String creat = playerCreatures[i];
    int creatureNumber = i + 1;
    String creatureType= creat.substring(0, creat.indexOf(":"));
    // 获取生物属性
    String[] creatureAttributes = creat.substring((creatureType + ":").length() + 1, 
                                  creat.length() - 1).split("\\s{0,},\\s{0,}");
        
    System.out.println("\t生物 #" + creatureNumber);
    System.out.println("\t\t生物类型: " + creatureType);
    for (int j = 0; j < creatureAttributes.length; j++) {
        System.out.println("\t\t\t属性 #" + (j + 1) + ": " + creatureAttributes[j]);
    }
}

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

玩家 #1
生物 #1
生物类型: O
属性 #1: o1
属性 #2: Brasil
属性 #3: F1
属性 #4: G2
属性 #5: E1
生物 #2
生物类型: G
属性 #1: g1
属性 #2: Germany
属性 #3: D2
属性 #4: V2
属性 #5: F1
属性 #6: G2
属性 #7: E1
生物 #3
生物类型: N
属性 #1: n1
属性 #2: Albania
属性 #3: D2
属性 #4: V2
属性 #5: R2
属性 #6: E1
属性 #7: A2

bracketsMaxDepth() 方法:

/**
 * 该方法接受一个字符串并返回嵌套括号的最大深度。要检查深度的括号类型在 bracketType 参数中提供。<br><br>
 *
 * @param bracketedString (String) 要处理的字符串。<br>
 *
 * @param bracketType     (String - 默认为 "()")可以提供一个开括号、闭括号,或者同时提供开括号和闭括号(无空格)。此方法将处理 4 种不同的括号类型之一,它们如下:<pre>
 *
 *      ()      圆括号       (默认)
 *      {}      花括号
 *      []      方括号
 *      &lt;&gt;      尖括号</pre>
 *
 * @return (Integer) 提供的括号类型的最大深度。如果提供的字符串中没有所提供类型的括号,则返回 0。如果所提供类型的字符串内存在不平衡,返回 -1。对于每个开括号,必须有一个闭括号,反之亦然。
 */
public static int bracketsMaxDepth(String bracketedString, String... bracketType) {
    // 方法实现,已略过...
}

getNestedBracketedGroups() 方法:

/**
 * 该方法将解析括号字符串中嵌套括号组的内容(提取),并将这些组的内容返回到 1D 字符串数组中。
 *
 * @param bracketedString     (String) 包含要解析的括号内容的字符串。<br>
 *
 * @param desiredDepth        (Integer) 默认为 0(完整深度)。要从中检索括号内容的嵌套深度。<br>
 *                            如果所提供的括号深度比所提供的输入字符串中包含的深度更深,则会抛出 IllegalArgumentException 异常,说明情况如此。
 *
 * @param bracketType         (String) 您必须提供要处理的括号类型。可以通过提供单个开括号或闭括号,或者同时提供开括号和闭括号来实现。例如,如果需要圆括号,则以下所有条

<details>
<summary>英文:</summary>

To do this I provide two specific methods which can be useful for other things other than this particular task. 

The first method is the **bracketsMaxDepth()** method which returns the the depth of a particular nested bracket. Supported brackets are `(), [], {}, &lt;&gt;`. The brackets you&#39;re interest in are the curly braces ( **{ }** ).

The second method is the **getNestedBracketedGroups()** method which will parse out (retrieve) the contents of nested brackets groups within a bracketed string and return those group contents within a Single Dimensional (1D) String Array. Supported brackets are `(), [], {}, &lt;&gt;`. The brackets you&#39;re interest in are the curly braces ( **{ }** ).

The **bracketsMaxDepth()** method is used internally by the **getNestedBracketedGroups()** method. As an example, to parse out the the following string:

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

we might do something like this (I added an extra creature for testing):

    String line = &quot;1:{O:{o1,Brasil,F1,G2,E1},G:{g1,Germany,D2,V2,F1,G2,E1},N:{n1,Albania,D2,V2,R2,E1,A2}}&quot;;
    line = line.trim();
        
    // Get player Number
    String player = line.substring(0, line.indexOf(&quot;:&quot;));
    // Is the player a string representation of a integer number?
    if (!player.matches(&quot;\\d+&quot;)) { 
        // Nope...exit
        return; // or whatever exit mechanism you need to use.
    }
    int playerNumber = Integer.parseInt(player);
        
    // Get Player&#39;s Creatures...
    String[] playerCreatures = getNestedBracketedGroups(line, 1, &quot;{}&quot;, 
                                true)[0].split(&quot;,(?![^\\{\\}]*\\})&quot;);
        
    // Display creatures data
    System.out.println(&quot;Creatures for Player #&quot; + playerNumber);
    for (int i = 0; i &lt; playerCreatures.length; i++) {
        String creat = playerCreatures[i];
        int creatureNumber = i + 1;
        String creatureType= creat.substring(0, creat.indexOf(&quot;:&quot;));
        // Get creature Attributes
        String[] creatureAttributes = creat.substring((creatureType + &quot;:&quot;).length() + 1, 
                                      creat.length() - 1).split(&quot;\\s{0,},\\s{0,}&quot;);
            
        System.out.println(&quot;\tCreature #&quot; + creatureNumber);
        System.out.println(&quot;\t\tCreature Type: &quot; + creatureType);
        for (int j = 0; j &lt; creatureAttributes.length; j++) {
            System.out.println(&quot;\t\t\tAttribute #&quot; + (j + 1) + &quot;: &quot; + creatureAttributes[j]);
        }
    }

The parsed output to Console Window would look like:

    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

----------

&gt; 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.&lt;br&gt;&lt;br&gt;
     *
     * @param bracketedString (String) The string to process.&lt;br&gt;
     *
     * @param bracketType     (String - Default is &quot;()&quot;) 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 &lt;b&gt;one&lt;/b&gt; of 4 different
     *                        bracket types and they are as follows:&lt;pre&gt;
     *
     *      ()      Parentheses       (Default)
     *      {}      Curly Braces
     *      []      Square Brackets
     *      &amp;lt;&amp;gt;      Chevron Brackets&lt;/pre&gt;
     *
     * @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 = &#39;(&#39;;    // Default
        char close = &#39;)&#39;;   // Default
        if (bracketType.length &gt; 0) {
            String bType = Character.toString(bracketType[0].charAt(0));
            switch (bType) {
                case &quot;(&quot;:
                case &quot;)&quot;:
                    open = &#39;(&#39;;
                    close = &#39;)&#39;;
                    break;
                case &quot;{&quot;:
                case &quot;}&quot;:
                    open = &#39;{&#39;;
                    close = &#39;}&#39;;
                    break;
                case &quot;[&quot;:
                case &quot;]&quot;:
                    open = &#39;[&#39;;
                    close = &#39;]&#39;;
                    break;
                case &quot;&lt;&quot;:
                case &quot;&gt;&quot;:
                    open = &#39;&lt;&#39;;
                    close = &#39;&gt;&#39;;
                    break;
                default:
                    throw new IllegalArgumentException(&quot;\nbracketsMaxDepth() Method Error!\n&quot;
                            + &quot;Unknown bracket type supplied (&quot; + bType + &quot;)!\n&quot;);
            }
        }

        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 &lt; n; i++) {
            if (c[i] == open) {
                current_max++;
                // update max if required
                if (current_max &gt; max) {

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

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

        return max;
    }

----------

&gt; 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&#39;s
     * say we have the following bracketed string:
     * &lt;pre&gt;
     *
     *      String a = &quot;1(2(3)(4))(5(6)(7))&quot;;&lt;/pre&gt;&lt;br&gt;
     * &lt;p&gt;
     * 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:
     * &lt;pre&gt;
     *
     *       Level 1         Level 2
     *      (2(3)(4))        (3) (4)
     *
     * ==================================
     *
     *       Level 1         Level 2
     *       (5(6)(7))       (6) (7)&lt;/pre&gt;&lt;br&gt;
     * &lt;p&gt;
     * Bracketed groups: &lt;b&gt;(2(3)(4))&lt;/b&gt; and &lt;b&gt;(5(6)(7))&lt;/b&gt; 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: &lt;b&gt;(3)&lt;/b&gt; &amp;
     * &lt;b&gt;(4)&lt;/b&gt; and &lt;b&gt;(6)&lt;/b&gt; &amp; &lt;b&gt;
     * (7)&lt;/b&gt;.&lt;br&gt;&lt;br&gt;
     * &lt;p&gt;
     * This method also utilizes the TokenJar&#39;s StringUtils.BracketsMaxDepth()
     * method.
     *
     * @param bracketedString     (String) The string which contains bracketed
     *                            content to parse.&lt;br&gt;
     *
     * @param desiredDepth        (Integer) Default is 0 (full depth). The
     *                            nested depth to retrieve bracketed content
     *                            from.&lt;br&gt; If the bracket depth supplied is
     *                            deeper than what is contained within the
     *                            supplied input string then an &lt;b&gt;IllegalArgu-
     *                            mentException&lt;/b&gt; 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:&lt;pre&gt;
     *
     *      &quot;(&quot;     &quot;)&quot;     &quot;()&quot;    &quot;)(&quot;&lt;/pre&gt;&lt;br&gt;
     *
     * Any one of four (4) bracket types can be supplied. The allowable Bracket
     * Types are:
     * &lt;pre&gt;
     *
     *      ()      Parentheses
     *      {}      Curly Braces
     *      []      Square Brackets
     *      &amp;lt;&amp;gt;      Chevron Brackets&lt;/pre&gt;
     *
     * @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.&lt;br&gt;
     *
     * @return (1D String Array) The determined nested groups desired.&lt;br&gt;
     *
     * @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 &gt; 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(&quot;\n\ngetNestedBracketedGroups() Method Error!\n&quot;
                    + &quot;Brackets mismatch in supplied string!\n&quot;);
        }
        else if (d &lt; desiredDepth) {
            // Throw Another Exception...
            throw new IllegalArgumentException(&quot;\n\ngetNestedBracketedGroups() Method Error!\n&quot;
                    + &quot;Invalid Depth Supplied! Brackets within the supplied string go to a\n&quot;
                    + &quot;maximum depth of (&quot; + d + &quot;) and therefore can not go to the supplied &quot;
                    + &quot;depth\nof (&quot; + desiredDepth + &quot;). Change the desired depth.\n&quot;);
        }

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

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

                if (depth &lt; 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 = &quot;&quot;;
                }

                continue;
            }
            if (c[i] == close) {
                depth--;
            }
            if (!strg.equals(&quot;&quot;)) {
                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 = &quot;&quot;;
            }
        }
        if (!strg.equals(&quot;&quot;)) {
            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()]);
    }

</details>



huangapple
  • 本文由 发表于 2020年4月5日 01:31:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61032064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定