title: How to access and manipulate strings in Stata variable labels?
body: <p>I have a Stata dataset with variable labels describing the year of measurement. I need to access the year of measurement from the variables to later rename each variable using a suffix showing the year. For example <code>V95</code> has a label <code>GNP/CAPITA,75</code>, and I want to rename it to <code>gnp_capita_75</code>. Some variables have labels like <code>GNP/C:GROWTH RTS,60-75</code>, and I want to add the midpoint of the interval after the comma to the variable name.</p>
  
  <p>So far my code for accessing the variable labels looks like this:</p>
  
  <pre><code>local varlist  V1 V2 V3 V28 V29 V30 V85 V86 V87 V88 V89 V90 V91 V92 V93 V94
  foreach variable in `varlist' {
      //get the label of the variable
      local label : var label `variable'
  
      //find the position of the comma
      local commapos : strpos(`label', ",")
  
      //find the stub before the comma
      local namestub : substr(`label', 1, `commapos' - 1)
  
      //find year after the comma
      local year : substr(`label', `commapos' + 1, `commapos' + 2)
  
      //replace any illegal character (%,/,:," ") with underscores:
      local namestub : subinstr(`namestub', "%", "_")
      local namestub : subinstr(`namestub', "/", "_")
      local namestub : subinstr(`namestub', ":", "_")
      local namestub : subinstr(`namestub', " ", "_")
  
      //rename variable with the new stub and the year 
      rename `variable' `namestub'`year'
  }
  </code></pre>
  
  <p>I get an error saying that strpos() is not allowed. Is it because I'm trying to make that a local macro? The examples I saw use it to generate a variable in the dataset, but I'm dealing with the variable labels. 
  Am I in the right direction here? How do I fix this error? </p>