Reputation: 271
I want to replace every single character in a string that matches a certain pattern. Take the following string
mystring <- c("000450")
I want to match all single zeros up to the first element that is non-zero. I tried something like
gsub("^0[^1-9]*", "x", mystring)
[1] "x450"
This expression replaces all the leading zeros with a single x
. But instead, I want to replace all three leading zeros with xxx
. The preferred result would be
[1] "xxx450"
Can anyone help me out?
Upvotes: 9
Views: 385
Reputation: 626690
You may use
mystring <- c("000450")
gsub("\\G0", "x", mystring, perl=TRUE)
## => [1] "xxx450"
See the regex demo and an R demo
The \\G0
regex matches 0
at the start of the string, and any 0
that only appears after a successful match.
Details
\G
- an anchor that matches ("asserts") the position at the start of the string or right after a successful match0
- a 0
char.Upvotes: 11