Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As @axtavt pointed out, you can discover directly whether a group participated in the match or not. You don't even have to change the regex; you already have one capturing group for each alternative. I like to use the <code>start(n)</code> method for the tests because it seems neater, but checking <code>group(n)</code> for a null value (as @axtavt did) yields the same result. Here's an example:</p> <pre><code>private static void processFile(ArrayList&lt;String&gt; lines) { Pattern p = Pattern.compile( "Object name\\.{7}: (.++)|" + "\\{CAT=([^\\}]++)\\}|" + "\\{CODE=([^\\}]++)\\}|" + "\\{DESC=([^\\}]++)\\}"); // Create the Matcher now and reassign it to each line as we go. Matcher m = p.matcher(""); for (String line : lines) { if (m.reset(line).find()) { // If group #n participated in the match, start(n) will be non-negative. if (m.start(1) != -1) { System.out.printf("%ncreating new component...%n"); System.out.printf(" name: %s%n", m.group(1)); } else if (m.start(2) != -1) { System.out.printf(" category: %s%n", m.group(2)); } else if (m.start(3) != -1) { System.out.printf(" order code: %s%n", m.group(3)); } else if (m.start(4) != -1) { System.out.printf(" description: %s%n", m.group(4)); } } } } </code></pre> <p>However, I'm not sure I agree with your reasoning about repeating part of the string in the code. If the data format changes, or you change which fields you extract, it seems like it would be easier to get out of sync when you update the code. In other words, your current code isn't redundant, it's self-documenting. :D</p> <p><strong>EDIT:</strong> You mentioned in a comment the possibility of processing the whole file at once instead of line by line. That's actually the easier way:</p> <pre><code>private static void processFile(String contents) { Pattern p = Pattern.compile( "Object name\\.{7}: (.++)|" + "\\{CAT=([^\\}]++)\\}|" + "\\{CODE=([^\\}]++)\\}|" + "\\{DESC=([^\\}]++)\\}"); Matcher m = p.matcher(contents); while (m.find()) { if (m.start(1) != -1) { System.out.printf("%ncreating new component...%n"); System.out.printf(" name: %s%n", m.group(1)); } else if (m.start(2) != -1) { System.out.printf(" category: %s%n", m.group(2)); } else if (m.start(3) != -1) { System.out.printf(" order code: %s%n", m.group(3)); } else if (m.start(4) != -1) { System.out.printf(" description: %s%n", m.group(4)); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload