title: Regex to remove leading zeros in R, unless the final (or only) character is zero
body: <pre><code>gsub("(?&lt;![0-9])0+", "", c("005", "0AB", "000", "0"), perl = TRUE)
  #&gt; [1] "5"  "AB" ""   ""
  gsub("(^|[^0-9])0+", "\\1", c("005", "0AB", "000", "0"), perl = TRUE)
  #&gt; [1] "5"  "AB" ""   ""
  </code></pre>
  
  <p>The regular expression above <a href="https://stackoverflow.com/questions/23538576/removing-leading-zeros-from-alphanumeric-characters-in-r">is from this SO thread</a> explaining how to remove <em>all</em> leading zeros from a string in R. As a consequence of this regular expression both "000" and "0" are transformed into "". Instead I want to remove all leading zeros from a string of characters, except for the cases when the final character happens to be zero, or the only character is zero.</p>
  
  <pre><code>"005" would become "5"
  "0AB" would become "AB"
  "000" would become "0"
  "0"   would become "0"
  </code></pre>
  
  <p><a href="https://stackoverflow.com/questions/5678455/remove-leading-zeroes-but-not-all-zeroes">This other SO thread</a> explains how to do what I want, but I don't think I'm getting the syntax quite correct, applying the solution in R. And I don't really understand the distinction between the 1st and 2nd solution below (if they indeed worked).</p>
  
  <pre><code>gsub("s/^0*(\d+)$/$1/;", "", c("005", "0AB", "000", "0"), perl = TRUE)  # 1st solution
  # Error: '\d' is an unrecognized escape in character string starting ""s/^0*(\d"
  gsub("s/0*(\d+)/$1/;", "", c("005", "0AB", "000", "0"), perl = TRUE)    # 2nd solution
  # Error: '\d' is an unrecognized escape in character string starting ""s/0*(\d"
  </code></pre>
  
  <p>What is the proper regex in R to get what I want?</p>