简体   繁体   English

R:格式化字符串并填充0

[英]R: format string and fill with 0

Is there a function in R to get the following. R里面有没有function得到下面的。 Let's say i have some inputs like c("1456-3-13;11:56:98", "45:76:12", "981-56-54;11") .假设我有一些输入,例如c("1456-3-13;11:56:98", "45:76:12", "981-56-54;11") However, they all should be in in the form of the regex "/d{4}-/d{2}-/d{2};/d{2}:/d{2}:/d{2}"但是,它们都应采用正则表达式"/d{4}-/d{2}-/d{2};/d{2}:/d{2}:/d{2}"的形式

Whenever a number is missing in the input it should be filled with zeros from left to right.每当输入中缺少一个数字时,它应该从左到右用零填充。 So the output of processing the mentioned inputs should be c("1456-03-13;11:56:98", "0000-00-00;45:76:12", "0981-56-54;11:00:00").所以处理上述输入的 output 应该是c("1456-03-13;11:56:98", "0000-00-00;45:76:12", "0981-56-54;11:00:00").

Any idea how to do this in a clever way?:)知道如何巧妙地做到这一点吗?:)

This is a bit messy, but it seems to work for this case.这有点混乱,但它似乎适用于这种情况。 First I parse the string you have and convert to numeric, then I reformat all the values首先我解析你的字符串并转换为数字,然后我重新格式化所有值

tests<-c("1456-3-13;11:56:98", "45:76:12", "981-56-54;11", "1456-3-13")

matches<- stringr::str_match(tests, "(?:(\\d+(?=[-;]))(?:-(\\d+)(?:-(\\d+))?)?)?;?(\\d+)?(?::(\\d+)(?::(\\d+))?)?")
matches <- matches[,-1]
class(matches) <- "numeric"
matches[is.na(matches)]<-0

do.call("sprintf", c(list("%04d-%02d-%02d;%02d:%02d:%02d"), lapply(1:ncol(matches), function(i) matches[, i])))

# [1] "1456-03-13;11:56:98" "0000-00-00;45:76:12" "0981-56-54;11:00:00"
# [4] "1456-03-13;00:00:00"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM