Removing leading zeros from alphanumeric characters in R

后端 未结 2 1719
夕颜
夕颜 2020-12-10 03:53

I have a character vector d with alphanumeric characters

d <- c(\"012309 template\", \"separate 00340\", \"00045\", \"890 098\", \"3405 gara         


        
2条回答
  •  执笔经年
    2020-12-10 04:41

    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("(?

    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"     
    >
    

提交回复
热议问题