Note that there are some explanatory texts on larger screens.

plurals
  1. POgroup counting issue with regex
    primarykey
    data
    text
    <p><B>EDIT: The RE in the original code is irrelevant (or that it makes any sense). Let's say you're matching <code>(X)|(Y)</code>: two patterns that are combined in the RE with an OR. How to know which pattern was actually matched??</b></p> <p>I'm trying to extract just the text that's mattching the RE <em>within</em> the brackets.</p> <p>The problem i'm facing is that i cannot figure out which <em>actual</em> group was matched, since the group index is <em>not</em> constant because of the OR.</p> <p>Ie in the line marked XXX <code>m.group()</code> returns the entire pattern</p> <pre><code>pat1 abcdef2 </code></pre> <p>And <code>m.group(1)</code> produces</p> <pre><code>pat null </code></pre> <p>And <code>m.group(2)</code> produces</p> <pre><code>null de </code></pre> <p>And <code>m.groupCount()</code> is just a total number of groups in the RE, so it is useless for indexing.</p> <p>What I want the loop to print is</p> <pre><code>pat de </code></pre> <p>It's a shame java doesnt have the perl's m/ operator that'll extract the stuff and put it nicely into an array ;-) </p> <pre><code>import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) throws IOException { Pattern p = Pattern.compile("([pat]+)1|abc([de]+)f2"); String original = " pat1 abcdef2555"; Matcher m = p.matcher(original); boolean result = m.find(); while (result) { System.out.println(m.group()); // XXX want to print only matched GROUP!! result = m.find(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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