【问题标题】:Removing leading zeros from alphanumeric characters in R从R中的字母数字字符中删除前导零
【发布时间】:2014-06-25 15:45:45
【问题描述】:

我有一个带有字母数字字符的字符向量 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"  

如何从 R 中的所有数字中删除前导零? as.numeric 将仅删除数字或整数向量中的所有前导零。我试过gsubregex,但没有得到想要的结果。

预期的输出如下

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

【问题讨论】:

    标签: regex string r character gsub


    【解决方案1】:

    除非前面有数字,否则您可以使用否定的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"     
    

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

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

    【讨论】:

    • 这也删除了数字字符串中的多个零,例如。 100001 到 101。
    • @Crops 现在应该修复了。
    【解决方案2】:

    这是利用 stringi 包中的 stri_replace_all_regex 的解决方案:

    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"   
    

    解释:我们正在匹配单词边界内的所有数字序列 (\b)。尾随零被贪婪地匹配(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"  
    

    【讨论】:

    • '\\d+' 呢?
    • 已编辑:\d 表示任意数字,\d+ 表示它们的非空序列
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2011-04-09
    • 2021-02-06
    • 1970-01-01
    • 2014-04-12
    • 2015-12-25
    • 1970-01-01
    相关资源
    最近更新 更多