title: Stata regular expressions
body: <p>I need to use a regular expression to extract a part of a string variable. My data looks like this where <em>a</em> represents alpha characters <em>x</em> and <em>Z</em> represent numerical characters. I want to extract the <em>Z</em> characters before the "-"</p>
  
  <pre><code>   var1
      "aaa xxx xxx ZZZ-ZZZ-a"
      "aaa xx xxx ZZZ-ZZ"
  </code></pre>
  
  <p>My code looks like this </p>
  
  <p><code>gen p_id = regexs(1) if regexm(var1, "([0-9][0-9][0-9])[-]*[0-9][0-9][-]*[ a-zA-Z]*$"</code>)</p>
  
  <p>This code extracts more than what is required. For example, this code extracts the numerical portion from an observation that looks like this. specifically it extracts <em>ZZZ</em> </p>
  
  <pre><code>var1
  "aaa ZZZZZ aaa"
  </code></pre>
  
  <p>I played around with expressions but cannot get the required answer. </p>