Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

r - Replace every single character at the start of string that matches a regex pattern

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 match
  • 0 - a 0 char.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...