每标题,我正在寻找一种方法,以删除两个连字号两侧的前导零。
codes <- c("0002-01014", "0020-0014","00014-00010")
want <- c("2-1014","20-14","14-10")我想可以将数字分成两部分,去掉前导零,然后粘贴到一起,但我想知道是否有更精确的方法使用str_extract()、str_replace()或相似的一步。
编辑:
我目前正在使用
str_split("0002-01010","-",simplify=T) %>%
str_replace("^0+(?!$)", "") %>%
str_c(collapse="-")我很好奇是否有一种可以在单行中实现的方法。
发布于 2021-01-27 20:26:40
发布于 2021-01-27 22:07:40
你最好在破折号开始或之后匹配和移除零,而不是在终点或破折号之前:
codes <- c("0002-01014", "0020-0014","00014-00010", "00000-000330")
gsub("(^|-)0+(?!-|$)", "\\1", codes, perl=TRUE)表达式解释
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
0+ '0' (1 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of look-aheadhttps://stackoverflow.com/questions/65926745
复制相似问题