正则表达式 – 从R中的字母数字字符中删除前导零

前端之家收集整理的这篇文章主要介绍了正则表达式 – 从R中的字母数字字符中删除前导零前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带字母数字字符的字符向量d
  1. d <- c("012309 template","separate 00340","00045","890 098","3405 garage","matter00908")
  2.  
  3. d
  4. [1] "012309 template" "separate 00340" "00045" "890 098" "3405 garage" "matter00908"

如何从R中的所有数字中删除前导零?
as.numeric将仅在数字或整数向量中删除所有前导零.我已尝试使用正则表达式gsub但无法获得所需的结果.

预期输出如下

  1. out <- c("12309 template","seperate 340","45","890 98","matter908")
  2. out
  3. [1] "12309 template" "seperate 340" "45" "890 98" "3405 garage" "matter908"
你可以使用负向lookbehind来消除0,除非前面有一个数字:
  1. > d <- c("100001","012309 template","matter00908")
  2. > gsub("(?<![0-9])0+","",d,perl = TRUE)
  3. [1] "100001" "12309 template" "separate 340" "45"
  4. [5] "890 98" "3405 garage" "matter908"

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

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

猜你在找的正则表达式相关文章