Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

regex - Removing leading zeros from alphanumeric characters in R

I have a character vector d with alphanumeric characters

d <- c("012309 template", "separate 00340", "00045", "890 098", "3405 garage", "matter00908")

d
[1] "012309 template" "separate 00340"  "00045"           "890 098"         "3405 garage"     "matter00908"  

How can I remove the leading zeros from all the numbers in R? as.numeric will remove all leading zeros only in numeric or integer vectors. I have tried gsub with regex but could not get the desired results.

The expected output is as follows

out <- c("12309 template", "seperate 340", "45", "890 98", "3405 garage", "matter908")
out
[1] "12309 template" "seperate 340"   "45"             "890 98"         "3405 garage"    "matter908"  
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You could use a negative lookbehind to eliminate 0 unless preceded by a digit:

> d <- c("100001", "012309 template", "separate 00340", "00045", "890 098", "3405 garage", "matter00908")
> gsub("(?<![0-9])0+", "", d, perl = TRUE)
[1] "100001"         "12309 template" "separate 340"   "45"            
[5] "890 98"         "3405 garage"    "matter908"     

Another way using regex:

> gsub("(^|[^0-9])0+", "\1", d, perl = TRUE)
[1] "100001"         "12309 template" "separate 340"   "45"            
[5] "890 98"         "3405 garage"    "matter908"     
>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...