提取r中字符串中存在的天数

时间:2019-05-24 10:23:33

标签: r split

我想将字符串中出现的天数提取到列表中。赞赏是否有人可以建议简单的方法。

x<- 'At 02:04 AM, 09:04 AM, 03:04 PM and 08:04 PM, on day 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10 of the month'

在类似"21" "22" "23" "24" "25" "26" "27" "28" "29" "30" "31" "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"的列表中期望结果

2 个答案:

答案 0 :(得分:2)

我们可以尝试匹配以下模式:

   number
0  0.00043

示例脚本:

number float64
dtype: object

用于匹配的正则表达式模式:

   number
0  0.00043038405

请注意,此处的负向前进\b\d{1,2}\b(?!:\d{2}) 非常必要,因为它可以避免意外地将小时/分钟时间戳中的数字匹配。

答案 1 :(得分:0)

我会那样做:

library(stringr)
days <- c(
# separated by commas
as.numeric(str_extract_all(str_extract_all(x, ' \\d+,'), '\\d+')[[1]]), 
# in the 'and {day_num} of' text
as.numeric(str_extract_all(str_extract_all(x, 'and \\d+ of'), '\\d+')[[1]])
)

您当然可以将两个regex ps合并在一起,但是我还是更喜欢这个,因为此答案有意区分了可以找到日数的两个不同上下文。