Replace each character matching the regex pattern

I want to replace each character in a string matching a specific pattern. Take the following line

mystring <- c("000450") 

I want to match all single zeros to the first non-zero element. I tried something like

 gsub("^0[^1-9]*", "x", mystring) [1] "x450" 

This expression replaces all leading zeros with one 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?

+7
regex r
source share
1 answer

you can use

 mystring <- c("000450") gsub("\\G0", "x", mystring, perl=TRUE) ## => [1] "xxx450" 

Watch a demo of regex and R demo

The regular expression \\G0 matches 0 at the beginning of the line and any 0 that appears only after a successful match.

More details

  • \G - binding that matches ("approves") the position at the beginning of the line or immediately after a successful match
  • 0 - a 0 char.
+9
source share

All Articles