title: Java + Regex: matching characters from a customized set that are not preceded by characters in the same set
body: <p>I am running into a silly problem with Regular Expressions in Java where I would like to match a String that begins with @ with characters from a certain valid set, but are not preceded by characters from the same valid set.</p>
  
  <p>The terms I would like to match are of the form:</p>
  
  <p>"y" + @ + "xxxxxxx"</p>
  
  <p>where:</p>
  
  <ul>
  <li>x is a character that belongs to the valid set <code>[a-zA-Z\\d\\-\\_]</code></li>
  <li>the @ sign appears once</li>
  <li>y is a character that does <strong>not</strong> belong to the valid set <code>[a-zA-Z\\d\\-\\_]</code></li>
  </ul>
  
  <p>I'm currently trying to do this this by using the following regular expressions pattern</p>
  
  <pre><code>MY_PATTERN = "[^[A-Za-z\\d\\-\\_]?]" + "@{1}" + "[A-Za-z\\d\\-\\_]+"
  String text = "12a@cat123-_     @dog123__- ";
  Pattern p = Pattern.compile(PATTERN);
  Matcher m = p.matcher(text);
  </code></pre>
  
  <p>Based on this I expect the following code to only print <code>@dog123__-</code></p>
  
  <p><code>while(m.find()){
     String s = m.group();
     System.out.println(s);
  }</code></p>
  
  <p>However it also prints out <code>a@cat123-_</code>.</p>
  
  <p>Could someone explain what I'm doing wrong?</p>