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" "" ""
上面的正则表达式来自此SO线程,它说明了如何从R中的字符串中删除所有前导零。由于此正则表达式,“ 000”和“ 0”都转换为“”。相反,我想从字符串中删除所有前导零,但最终字符恰好为零或唯一字符为零的情况除外。
"005" would become "5"
"0AB" would become "AB"
"000" would become "0"
"0" would become "0"
另一个SO线程解释了如何做我想做的事情,但是我认为我在使用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中正确的正则表达式是什么才能得到我想要的?
regex
菜鸟。什么是你的模式,这其中的性能差异(或其他偏好)^0*(.+)$
或^0+(.+)$
?