从R中的字母数字字符中删除前导零

Cro*_*ops 12 regex string r character gsub

我有一个d带字母数字字符的字符向量

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

d
[1] "012309 template" "separate 00340"  "00045"           "890 098"         "3405 garage"     "matter00908"  
Run Code Online (Sandbox Code Playgroud)

如何从R中的所有数字中删除前导零? as.numeric将仅在数字或整数向量中删除所有前导零.我尝试过gsub,regex但无法获得理想的结果.

预期输出如下

out <- c("12309 template", "seperate 340", "45", "890 98", "3405 garage", "matter908")
out
[1] "12309 template" "seperate 340"   "45"             "890 98"         "3405 garage"    "matter908"  
Run Code Online (Sandbox Code Playgroud)

dev*_*ull 22

您可以使用负向lookbehind来消除0,除非前面有一个数字:

> 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"     
Run Code Online (Sandbox Code Playgroud)

另一种使用正则表达式的方法:

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

  • @Crops应该现在修复。 (2认同)

gag*_*ews 10

下面是利用该解决方案stri_replace_all_regexstringi包:

d <- c("012309 template", "separate 00340", "00045",
       "890 098", "3405 garage", "matter00908")
library("stringi")
stri_replace_all_regex(d, "\\b0*(\\d+)\\b", "$1")
## [1] "12309 template" "separate 340"   "45"             "890 98"
## [5] "3405 garage"    "matter00908"   
Run Code Online (Sandbox Code Playgroud)

说明:我们匹配单词边界(\b)中的所有数字序列.尾随零与greedily(0+)匹配.其余数字(\d表示任何数字, \d+表示其非空序列)在组((...))内捕获.然后我们只用组捕获的东西替换所有这些匹配.

如果您还希望删除单词中的0(如您的示例所示),只需省略\b并调用:

stri_replace_all_regex(d, "0*(\\d+)", "$1")
## [1] "12309 template" "separate 340"   "45"             "890 98"
## [5] "3405 garage"    "matter908"  
Run Code Online (Sandbox Code Playgroud)