Regex to remove leading zeros in R, unless the final (or only) character is zero
You could use an alternation to either match all the zeroes in the string in a capturing group or match all the zeroes from the start of the string.
In the replacement use group 1.
^0*(0)$|^0+
Regex demo | R demo
For example
sub("^0*(0)$|^0+", "\\1", c("005", "0AB", "000", "0"))
Output
[1] "5" "AB" "0" "0"
Or even better as commented by Wiktor Stribiżew, you could use capture a single 0 in a group and repeat the group itself to capture the last instance of a zero.
^(0)+$|^0+
Regex demo
You may remove all zeros from the start of a string but not the last one:
sub("^0+(?!$)", "", x, perl=TRUE)
See the regex demo.
Details
^
- start of a string0+
- one or more zeros(?!$)
- a negative lookahead that fails the match if there is an end of string position immediately to the right of the current location
See the R demo:
x <- c("005", "0AB", "000", "0")
sub("^0+(?!$)", "", x, perl=TRUE)
## => [1] "5" "AB" "0" "0"
We can add one more condition with a regex lookaround to check for any non-zero values after one or more zeros (0+
)
sub("(?<![0-9])0+(?=[^0])", "", sub("^0+$", "0", v1), perl = TRUE)
#[1] "5" "AB" "0" "0"
data
v1 <- c("005", "0AB", "000", "0")