如何在Java中处理一行?

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

How to process a line in Java?

问题

以下是翻译好的部分:

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

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

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

英文:

The format of line in question is:

  1. 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() 方法。例如,要解析以下字符串:

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

我们可以这样做(我添加了一个额外的元素进行测试):

  1. 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}}";
  2. line = line.trim();
  3. // 获取玩家编号
  4. String player = line.substring(0, line.indexOf(":"));
  5. // 玩家是一个整数表示的字符串吗?
  6. if (!player.matches("\\d+")) {
  7. // 不是的话...退出
  8. return; // 或者使用您需要的其他退出机制。
  9. }
  10. int playerNumber = Integer.parseInt(player);
  11. // 获取玩家的生物...
  12. String[] playerCreatures = getNestedBracketedGroups(line, 1, "{}",
  13. true)[0].split(",(?![^\\{\\}]*\\})");
  14. // 显示生物数据
  15. System.out.println("玩家 #" + playerNumber);
  16. for (int i = 0; i < playerCreatures.length; i++) {
  17. String creat = playerCreatures[i];
  18. int creatureNumber = i + 1;
  19. String creatureType= creat.substring(0, creat.indexOf(":"));
  20. // 获取生物属性
  21. String[] creatureAttributes = creat.substring((creatureType + ":").length() + 1,
  22. creat.length() - 1).split("\\s{0,},\\s{0,}");
  23. System.out.println("\t生物 #" + creatureNumber);
  24. System.out.println("\t\t生物类型: " + creatureType);
  25. for (int j = 0; j < creatureAttributes.length; j++) {
  26. System.out.println("\t\t\t属性 #" + (j + 1) + ": " + creatureAttributes[j]);
  27. }
  28. }

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

  1. 玩家 #1
  2. 生物 #1
  3. 生物类型: O
  4. 属性 #1: o1
  5. 属性 #2: Brasil
  6. 属性 #3: F1
  7. 属性 #4: G2
  8. 属性 #5: E1
  9. 生物 #2
  10. 生物类型: G
  11. 属性 #1: g1
  12. 属性 #2: Germany
  13. 属性 #3: D2
  14. 属性 #4: V2
  15. 属性 #5: F1
  16. 属性 #6: G2
  17. 属性 #7: E1
  18. 生物 #3
  19. 生物类型: N
  20. 属性 #1: n1
  21. 属性 #2: Albania
  22. 属性 #3: D2
  23. 属性 #4: V2
  24. 属性 #5: R2
  25. 属性 #6: E1
  26. 属性 #7: A2

bracketsMaxDepth() 方法:

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

getNestedBracketedGroups() 方法:

  1. /**
  2. * 该方法将解析括号字符串中嵌套括号组的内容(提取),并将这些组的内容返回到 1D 字符串数组中。
  3. *
  4. * @param bracketedString (String) 包含要解析的括号内容的字符串。<br>
  5. *
  6. * @param desiredDepth (Integer) 默认为 0(完整深度)。要从中检索括号内容的嵌套深度。<br>
  7. * 如果所提供的括号深度比所提供的输入字符串中包含的深度更深,则会抛出 IllegalArgumentException 异常,说明情况如此。
  8. *
  9. * @param bracketType (String) 您必须提供要处理的括号类型。可以通过提供单个开括号或闭括号,或者同时提供开括号和闭括号来实现。例如,如果需要圆括号,则以下所有条
  10. <details>
  11. <summary>英文:</summary>
  12. To do this I provide two specific methods which can be useful for other things other than this particular task.
  13. 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 ( **{ }** ).
  14. 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 ( **{ }** ).
  15. The **bracketsMaxDepth()** method is used internally by the **getNestedBracketedGroups()** method. As an example, to parse out the the following string:
  16. String line = &quot;1:{O:{o1,Brasil,F1,G2,E1},&quot; +
  17. &quot;G:{g1,Germany,D2,V2,F1,G2,E1},&quot; +
  18. &quot;N:{n1,Albania,D2,V2,R2,E1,A2}}&quot;;
  19. we might do something like this (I added an extra creature for testing):
  20. 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;;
  21. line = line.trim();
  22. // Get player Number
  23. String player = line.substring(0, line.indexOf(&quot;:&quot;));
  24. // Is the player a string representation of a integer number?
  25. if (!player.matches(&quot;\\d+&quot;)) {
  26. // Nope...exit
  27. return; // or whatever exit mechanism you need to use.
  28. }
  29. int playerNumber = Integer.parseInt(player);
  30. // Get Player&#39;s Creatures...
  31. String[] playerCreatures = getNestedBracketedGroups(line, 1, &quot;{}&quot;,
  32. true)[0].split(&quot;,(?![^\\{\\}]*\\})&quot;);
  33. // Display creatures data
  34. System.out.println(&quot;Creatures for Player #&quot; + playerNumber);
  35. for (int i = 0; i &lt; playerCreatures.length; i++) {
  36. String creat = playerCreatures[i];
  37. int creatureNumber = i + 1;
  38. String creatureType= creat.substring(0, creat.indexOf(&quot;:&quot;));
  39. // Get creature Attributes
  40. String[] creatureAttributes = creat.substring((creatureType + &quot;:&quot;).length() + 1,
  41. creat.length() - 1).split(&quot;\\s{0,},\\s{0,}&quot;);
  42. System.out.println(&quot;\tCreature #&quot; + creatureNumber);
  43. System.out.println(&quot;\t\tCreature Type: &quot; + creatureType);
  44. for (int j = 0; j &lt; creatureAttributes.length; j++) {
  45. System.out.println(&quot;\t\t\tAttribute #&quot; + (j + 1) + &quot;: &quot; + creatureAttributes[j]);
  46. }
  47. }
  48. The parsed output to Console Window would look like:
  49. Creatures for Player #1
  50. Creature #1
  51. Creature Type: O
  52. Attribute #1: o1
  53. Attribute #2: Brasil
  54. Attribute #3: F1
  55. Attribute #4: G2
  56. Attribute #5: E1
  57. Creature #2
  58. Creature Type: G
  59. Attribute #1: g1
  60. Attribute #2: Germany
  61. Attribute #3: D2
  62. Attribute #4: V2
  63. Attribute #5: F1
  64. Attribute #6: G2
  65. Attribute #7: E1
  66. Creature #3
  67. Creature Type: N
  68. Attribute #1: n1
  69. Attribute #2: Albania
  70. Attribute #3: D2
  71. Attribute #4: V2
  72. Attribute #5: R2
  73. Attribute #6: E1
  74. Attribute #7: A2
  75. ----------
  76. &gt; The **bracketsMaxDepth()** method:
  77. /**
  78. * This method takes a string and returns the maximum depth of nested
  79. * brackets. The bracket type to check the depth for is supplied within the
  80. * bracketType parameter.&lt;br&gt;&lt;br&gt;
  81. *
  82. * @param bracketedString (String) The string to process.&lt;br&gt;
  83. *
  84. * @param bracketType (String - Default is &quot;()&quot;) Either a open bracket,
  85. * or a close bracket, or both open and closed
  86. * brackets can be supplied (no white-spaces). This
  87. * method will process any &lt;b&gt;one&lt;/b&gt; of 4 different
  88. * bracket types and they are as follows:&lt;pre&gt;
  89. *
  90. * () Parentheses (Default)
  91. * {} Curly Braces
  92. * [] Square Brackets
  93. * &amp;lt;&amp;gt; Chevron Brackets&lt;/pre&gt;
  94. *
  95. * @return (Integer) The maximum depth of the supplied bracket type. 0 is
  96. * returned if there are no brackets of the type supplied within the
  97. * supplied string. -1 is returned if there is an unbalance within
  98. * the supplied string of the supplied bracket type. For every open
  99. * bracket there must be a close bracket and visa versa.
  100. */
  101. public static int bracketsMaxDepth(String bracketedString, String... bracketType) {
  102. char open = &#39;(&#39;; // Default
  103. char close = &#39;)&#39;; // Default
  104. if (bracketType.length &gt; 0) {
  105. String bType = Character.toString(bracketType[0].charAt(0));
  106. switch (bType) {
  107. case &quot;(&quot;:
  108. case &quot;)&quot;:
  109. open = &#39;(&#39;;
  110. close = &#39;)&#39;;
  111. break;
  112. case &quot;{&quot;:
  113. case &quot;}&quot;:
  114. open = &#39;{&#39;;
  115. close = &#39;}&#39;;
  116. break;
  117. case &quot;[&quot;:
  118. case &quot;]&quot;:
  119. open = &#39;[&#39;;
  120. close = &#39;]&#39;;
  121. break;
  122. case &quot;&lt;&quot;:
  123. case &quot;&gt;&quot;:
  124. open = &#39;&lt;&#39;;
  125. close = &#39;&gt;&#39;;
  126. break;
  127. default:
  128. throw new IllegalArgumentException(&quot;\nbracketsMaxDepth() Method Error!\n&quot;
  129. + &quot;Unknown bracket type supplied (&quot; + bType + &quot;)!\n&quot;);
  130. }
  131. }
  132. int current_max = 0; // current count
  133. int max = 0; // overall maximum count
  134. int n = bracketedString.length();
  135. char[] c = bracketedString.toCharArray();
  136. // Traverse the input string
  137. for (int i = 0; i &lt; n; i++) {
  138. if (c[i] == open) {
  139. current_max++;
  140. // update max if required
  141. if (current_max &gt; max) {
  142. max = current_max;
  143. }
  144. }
  145. else if (c[i] == close) {
  146. if (current_max &gt; 0) {
  147. current_max--;
  148. }
  149. else {
  150. return -1;
  151. }
  152. }
  153. }
  154. // finally check for unbalanced string
  155. if (current_max != 0) {
  156. return -1;
  157. }
  158. return max;
  159. }
  160. ----------
  161. &gt; The **getNestedBracketedGroups()** method:
  162. /**
  163. * This method will parse out (retrieve) the contents of nested brackets
  164. * groups within a bracketed string and return those group contents within a
  165. * 1D String Array. The best way to see how this works is by examples. Let&#39;s
  166. * say we have the following bracketed string:
  167. * &lt;pre&gt;
  168. *
  169. * String a = &quot;1(2(3)(4))(5(6)(7))&quot;;&lt;/pre&gt;&lt;br&gt;
  170. * &lt;p&gt;
  171. * In the above string we can see that there are two instances of level 1
  172. * bracketed groups which in each level 1 group nest two more level 2
  173. * bracketed groups:
  174. * &lt;pre&gt;
  175. *
  176. * Level 1 Level 2
  177. * (2(3)(4)) (3) (4)
  178. *
  179. * ==================================
  180. *
  181. * Level 1 Level 2
  182. * (5(6)(7)) (6) (7)&lt;/pre&gt;&lt;br&gt;
  183. * &lt;p&gt;
  184. * Bracketed groups: &lt;b&gt;(2(3)(4))&lt;/b&gt; and &lt;b&gt;(5(6)(7))&lt;/b&gt; are both
  185. * considered to be at nest level 1 (level 1 is the outer most level). They
  186. * are both individual groups because they both have their own set of outer
  187. * brackets. Within each level 1 group we have two sets of level 2 bracketed
  188. * groups (4 level 2 groups altogether) which consist of: &lt;b&gt;(3)&lt;/b&gt; &amp;
  189. * &lt;b&gt;(4)&lt;/b&gt; and &lt;b&gt;(6)&lt;/b&gt; &amp; &lt;b&gt;
  190. * (7)&lt;/b&gt;.&lt;br&gt;&lt;br&gt;
  191. * &lt;p&gt;
  192. * This method also utilizes the TokenJar&#39;s StringUtils.BracketsMaxDepth()
  193. * method.
  194. *
  195. * @param bracketedString (String) The string which contains bracketed
  196. * content to parse.&lt;br&gt;
  197. *
  198. * @param desiredDepth (Integer) Default is 0 (full depth). The
  199. * nested depth to retrieve bracketed content
  200. * from.&lt;br&gt; If the bracket depth supplied is
  201. * deeper than what is contained within the
  202. * supplied input string then an &lt;b&gt;IllegalArgu-
  203. * mentException&lt;/b&gt; is thrown explaining as
  204. * such.
  205. *
  206. * @param bracketType (String) You must supply the bracket type to
  207. * process. This can be done by supplying either
  208. * a single open or close bracket or both open
  209. * and close brackets, for example, any one of
  210. * the following are all acceptable entries if
  211. * parentheses are required:&lt;pre&gt;
  212. *
  213. * &quot;(&quot; &quot;)&quot; &quot;()&quot; &quot;)(&quot;&lt;/pre&gt;&lt;br&gt;
  214. *
  215. * Any one of four (4) bracket types can be supplied. The allowable Bracket
  216. * Types are:
  217. * &lt;pre&gt;
  218. *
  219. * () Parentheses
  220. * {} Curly Braces
  221. * [] Square Brackets
  222. * &amp;lt;&amp;gt; Chevron Brackets&lt;/pre&gt;
  223. *
  224. * @param removeOuterBrackets (Optional - Boolean - Default is false) By
  225. * default the outer brackets for each found
  226. * group are also attached to the returned
  227. * results. If true is supplied to this optional
  228. * parameter then the outer brackets are removed
  229. * from the returned group results.&lt;br&gt;
  230. *
  231. * @return (1D String Array) The determined nested groups desired.&lt;br&gt;
  232. *
  233. * @throws IllegalArgumentException if a depth is supplied greater than the
  234. * available bracketed depth contained
  235. * within the supplied input string. This
  236. * exception is also thrown if it is found
  237. * that the supplied Bracket Type is
  238. * unbalanced (open and closed braces are
  239. * not properly paired) within the supplied
  240. * input string.
  241. */
  242. public static String[] getNestedBracketedGroups(String bracketedString, int desiredDepth,
  243. String bracketType, boolean... removeOuterBrackets) {
  244. boolean removeOuter = false;
  245. if (removeOuterBrackets.length &gt; 0) {
  246. removeOuter = removeOuterBrackets[0];
  247. }
  248. int d = bracketsMaxDepth(bracketedString, bracketType);
  249. if (desiredDepth == 0) {
  250. //Default for this method is 0 (full depth).
  251. desiredDepth = 1;
  252. }
  253. if (d == -1) {
  254. // Throw Exception...
  255. throw new IllegalArgumentException(&quot;\n\ngetNestedBracketedGroups() Method Error!\n&quot;
  256. + &quot;Brackets mismatch in supplied string!\n&quot;);
  257. }
  258. else if (d &lt; desiredDepth) {
  259. // Throw Another Exception...
  260. throw new IllegalArgumentException(&quot;\n\ngetNestedBracketedGroups() Method Error!\n&quot;
  261. + &quot;Invalid Depth Supplied! Brackets within the supplied string go to a\n&quot;
  262. + &quot;maximum depth of (&quot; + d + &quot;) and therefore can not go to the supplied &quot;
  263. + &quot;depth\nof (&quot; + desiredDepth + &quot;). Change the desired depth.\n&quot;);
  264. }
  265. char open = &#39;(&#39;; // Default
  266. char close = &#39;)&#39;; // Default
  267. String bType = Character.toString(bracketType.charAt(0));
  268. switch (bType) {
  269. case &quot;(&quot;:
  270. case &quot;)&quot;:
  271. open = &#39;(&#39;;
  272. close = &#39;)&#39;;
  273. break;
  274. case &quot;{&quot;:
  275. case &quot;}&quot;:
  276. open = &#39;{&#39;;
  277. close = &#39;}&#39;;
  278. break;
  279. case &quot;[&quot;:
  280. case &quot;]&quot;:
  281. open = &#39;[&#39;;
  282. close = &#39;]&#39;;
  283. break;
  284. case &quot;&lt;&quot;:
  285. case &quot;&gt;&quot;:
  286. open = &#39;&lt;&#39;;
  287. close = &#39;&gt;&#39;;
  288. break;
  289. default:
  290. throw new IllegalArgumentException(&quot;\ngetNestedBracketedGroups() Method Error!\n&quot;
  291. + &quot;Unknown bracket type supplied (&quot; + bType + &quot;)!\n&quot;);
  292. }
  293. List&lt;String&gt; list = new ArrayList&lt;&gt;();
  294. int n = bracketedString.length();
  295. char[] c = bracketedString.toCharArray();
  296. int depth = 0;
  297. String strg = &quot;&quot;;
  298. for (int i = 0; i &lt; n; i++) {
  299. if (c[i] == open) {
  300. depth++;
  301. }
  302. if ((depth &gt;= desiredDepth)) {
  303. if (c[i] == close) {
  304. depth--;
  305. }
  306. strg += Character.toString(c[i]);
  307. if (depth &lt; desiredDepth) {
  308. strg = strg.trim();
  309. if (removeOuter) {
  310. if (strg.startsWith(Character.toString(open))) {
  311. strg = strg.substring(1);
  312. }
  313. if (strg.endsWith(Character.toString(close))) {
  314. strg = strg.substring(0,
  315. strg.lastIndexOf(Character.toString(close)));
  316. }
  317. }
  318. list.add(strg);
  319. strg = &quot;&quot;;
  320. }
  321. continue;
  322. }
  323. if (c[i] == close) {
  324. depth--;
  325. }
  326. if (!strg.equals(&quot;&quot;)) {
  327. strg = strg.trim();
  328. if (removeOuter) {
  329. if (strg.startsWith(Character.toString(open))) {
  330. strg = strg.substring(1);
  331. }
  332. if (strg.endsWith(Character.toString(close))) {
  333. strg = strg.substring(0,
  334. strg.lastIndexOf(Character.toString(close)));
  335. }
  336. }
  337. list.add(strg);
  338. strg = &quot;&quot;;
  339. }
  340. }
  341. if (!strg.equals(&quot;&quot;)) {
  342. strg = strg.trim();
  343. if (removeOuter) {
  344. if (strg.startsWith(Character.toString(open))) {
  345. strg = strg.substring(1);
  346. }
  347. if (strg.endsWith(Character.toString(close))) {
  348. strg = strg.substring(0,
  349. strg.lastIndexOf(Character.toString(close)));
  350. }
  351. }
  352. list.add(strg); // + Character.toString(close));
  353. }
  354. // (red(blue))grey((orange)green)
  355. return list.toArray(new String[list.size()]);
  356. }
  357. </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:

确定