我有几个约会要改。然而,我无法得到正则表达式,但这是我的替代尝试,但它是不必要的长。
library(stringr)
#date string vector, only two scenerios can be present
date <- c("3rd of June 18:09","22nd of January 22:19")
# substring will remove the string portion. I did not go
# with regex for this is because I am not that greate with it.
all_date_corrected <- c()
for(i in date){
if(nchar(stringr::word(i, 1))>=4){
x<- gsub(substr(i, start= 3, stop=7), "", i)
all_date_corrected <- c(all_date_corrected,
format(strptime(x,"%d %B %H:%M",tz="GMT"),
format="%m-%d %H:%M"))
}
else{
x<- gsub(substr(i, start= 2, stop=6), "", i)
all_date_corrected <- c(all_date_corrected,
format(strptime(x,"%d %B %H:%M",tz="GMT"),
format="%m-%d %H:%M"))
}
}
print(all_date_corrected) #[1] "06-03 18:09" "01-22 22:19"
我很确定我能用substr
& if- statement
摆脱gsub
。这是我的尝试。
gsub("([0-9]+).*?([A-Z])", "\\1", date[1]) #[1] "3une 18:09"
gsub("([0-9]+).*?([A-Z])", "\\1", date[2]) #[1] "22anuary 22:19"
正如你所看到的,我的模式是不断地消耗这封信,也不会留出空间。如果有人能帮忙就好了。谢谢。
发布于 2020-06-04 07:47:30
你可以试试这个。它以三个捕获组捕获日期、月份和时间,并返回一个适合于strptime
的字符串。
strptime(gsub("^(\\d+)\\w+ of (\\w+) (.*)$", "\\1 \\2 \\3", date), "%d %B %H:%M")
#> [1] "2020-06-03 18:09:00 BST" "2020-01-22 22:19:00 GMT"
解释
^(\\d+)
从string\\w+ of
匹配中捕获前面的数字,但不捕获th of
或rd of
(\\w+)
捕获整个月的name(.$)$
捕获最终空间之后的所有内容
"\\1 \\2 \\3"
意味着用空格分隔的三个捕获组替换每个字符串,例如"03 June 18:09"
。然后,我们可以使用strptime
捕获这一功能,使用%d
表示日期,使用%B
表示月份,使用%H:%M
捕获时间。
https://stackoverflow.com/questions/62198362
复制