首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >需要帮助想出一个在R中的正则表达式

需要帮助想出一个在R中的正则表达式
EN

Stack Overflow用户
提问于 2020-06-04 15:26:59
回答 1查看 37关注 0票数 1

我有几个约会要改。然而,我无法得到正则表达式,但这是我的替代尝试,但它是不必要的长。

代码语言:javascript
代码运行次数:0
运行
复制
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。这是我的尝试。

代码语言:javascript
代码运行次数:0
运行
复制
gsub("([0-9]+).*?([A-Z])", "\\1", date[1]) #[1] "3une 18:09"

gsub("([0-9]+).*?([A-Z])", "\\1", date[2]) #[1] "22anuary 22:19"

正如你所看到的,我的模式是不断地消耗这封信,也不会留出空间。如果有人能帮忙就好了。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-04 15:47:30

你可以试试这个。它以三个捕获组捕获日期、月份和时间,并返回一个适合于strptime的字符串。

代码语言:javascript
代码运行次数:0
运行
复制
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 ofrd of
  • (\\w+)捕获整个月的name
  • (.$)$捕获最终空间

之后的所有内容

"\\1 \\2 \\3"意味着用空格分隔的三个捕获组替换每个字符串,例如"03 June 18:09"。然后,我们可以使用strptime捕获这一功能,使用%d表示日期,使用%B表示月份,使用%H:%M捕获时间。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62198362

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档