title: java regex: (C identifier followed by __)
body: <p>I'm looking for a way to match a C identifier followed by a double-underscore. But here's the thing: I need it to be non-greedy if the identifier ends in a series of underscores.</p>
  
  <p>I almost got it with <code>^([_A-Za-z][_A-Za-z0-9]*?)__</code> but there's a tricky set of cases where the identifier can end in a series of underscores:</p>
  
  <pre><code>string          expected identifier
  abcd0__         abcd0
  abcd0___        abcd0_
  abcd0____       abcd0__
  abcd__0__       abcd
  abcd___0__      abcd_
  abcd____0__     abcd__
  </code></pre>
  
  <p>Is there a way I can modify the regex to produce the expected group match listed above?</p>
  
  <p>Below is a test program which prints the incorrect output:</p>
  
  <pre><code>abcd0__ -&gt; match is abcd0
  abcd0___ -&gt; match is abcd0
  abcd0____ -&gt; match is abcd0
  abcd__0__ -&gt; match is abcd
  abcd___0__ -&gt; match is abcd
  abcd____0__ -&gt; match is abcd
  </code></pre>
  
  <p>Regex3.java:</p>
  
  <pre><code>import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  
  public class Regex3 {
      final static private Pattern pattern = 
         Pattern.compile("^([_A-Za-z][_A-Za-z0-9]*?)__");
  
      static public void main(String[] args)
      {
          String[] items = {
                  "abcd0__",
                  "abcd0___",
                  "abcd0____",
                  "abcd__0__",
                  "abcd___0__"
                  "abcd____0__"
          };
          for (String item : items)
              test(item);
      }
      private static void test(String item) {
          Matcher m = pattern.matcher(item);
          if (m.find())
          {
              System.out.println(item+" -&gt; match is "+m.group(1));
          }
          else
          {
              System.out.println(item+" -&gt; no match");            
          }
      }
  }
  </code></pre>