title: Java regex for removing all characters except a pattern
body: <p>I have a string including e-mail. There are probably extra characters before and / or after it.
  input examples:</p>
  
  <pre><code>a1@b.com
  a2@b.com abcd efg
  x y z a3@b.com
  p q a4@b.com x z
  asd[x5@c.net]gh
  </code></pre>
  
  <p>I want to remove the extra characters.</p>
  
  <p>Desired outputs:</p>
  
  <pre><code>a1@b.com
  a2@b.com
  a3@b.com
  a4@b.com
  x5@c.net
  </code></pre>
  
  <p>Valid characters are a-zA-Z0-9._
  So there are probably invalid characters before and / or after e-mail.</p>
  
  <p>I tried this code to identify whether it is a correct email or not (this assumes that it is separated from extra characters by space), but I can not replace to the desired string (using s.replaceAll()):</p>
  
  <pre><code>if (s.matches("(?i).*\\s[a-zA-Z_\\.]+@[a-zA-Z_\\.]+\\.[a-zA-Z_\\.]+.*") ||
      fields[2].matches("(?i).*[a-zA-Z_\\.]+@[a-zA-Z_\\.]+\\.[a-zA-Z_\\.]+\\s.*"))
  </code></pre>