【发布时间】:2019-12-20 16:50:04
【问题描述】:
gsub("(?<![0-9])0+", "", c("005", "0AB", "000", "0"), perl = TRUE)
#> [1] "5" "AB" "" ""
gsub("(^|[^0-9])0+", "\\1", c("005", "0AB", "000", "0"), perl = TRUE)
#> [1] "5" "AB" "" ""
is from this SO thread 上面的正则表达式解释了如何从 R 中的字符串中删除 所有 前导零。由于这个正则表达式,“000”和“0”都被转换为“” .相反,我想从字符串中删除所有前导零,但最后一个字符恰好为零或唯一字符为零的情况除外。
"005" would become "5"
"0AB" would become "AB"
"000" would become "0"
"0" would become "0"
This other SO thread 解释了如何做我想做的事,但我认为我的语法不太正确,在 R 中应用解决方案。而且我不太了解第一个和第二个解决方案之间的区别下面(如果它们确实有效)。
gsub("s/^0*(\d+)$/$1/;", "", c("005", "0AB", "000", "0"), perl = TRUE) # 1st solution
# Error: '\d' is an unrecognized escape in character string starting ""s/^0*(\d"
gsub("s/0*(\d+)/$1/;", "", c("005", "0AB", "000", "0"), perl = TRUE) # 2nd solution
# Error: '\d' is an unrecognized escape in character string starting ""s/0*(\d"
R 中正确的正则表达式是什么?
【问题讨论】:
标签: r regex string gsub stringr