我试图从字符串中删除/提取时间。逻辑是我抓住的东西:
这是一个MWE和我尝试过的。我几乎在那里,但我不希望"6:33."
被提取,而是"6:33"
,因为冒号或逗号的出现必须后跟一个或多个数字。在这种情况下,句号的结尾不是时间的一部分。
text.var <- c("R uses 1:5 for 1, 2, 3, 4, 5.",
"At 3:00 we'll meet up and leave by 4:30:20.",
"We'll meet at 6:33.", "He ran it in :22.34.")
pattern <- "\\(?[0-9]{0,2}\\)?\\:\\(?[0-9]{2}\\)?\\(?[:.]{0,1}\\)?\\(?[0-9]{0,}\\)?"
regmatches(text.var, gregexpr(pattern, text.var, perl = TRUE))
## [[1]]
## character(0)
##
## [[2]]
## [1] "3:00" "4:30:20"
##
## [[3]]
## [1] "6:33."
##
## [[4]]
## [1] ":22.34"
所需输出
## [[1]]
## character(0)
##
## [[2]]
## [1] "3:00" "4:30:20"
##
## [[3]]
## [1] "6:33"
##
## [[4]]
## [1] ":22.34"
答案 0 :(得分:4)
如果我理解正确,您可以使用以下方法解决问题。
regmatches(text.var, gregexpr('\\d{0,2}:\\d{2}(?:[:.]\\d+)?', text.var, perl=T))
<强>解释强>:
\d{0,2} # digits (0-9) (between 0 and 2 times)
: # ':'
\d{2} # digits (0-9) (2 times)
(?: # group, but do not capture (optional):
[:.] # any character of: ':', '.'
\d+ # digits (0-9) (1 or more times)
)? # end of grouping
注意:我删除了转义的括号,因为我不清楚为什么它们首先被使用..
答案 1 :(得分:1)
这就是你想要的:
regmatches(text.var, gregexpr("(\\d{0,2}:\\d{2}(?:\\.\\d+)?)", text.var))
<强> Working demo 强>
MATCH 1
1. [42-46] `3:00`
MATCH 2
1. [74-78] `4:30`
MATCH 3
1. [78-81] `:20`
MATCH 4
1. [104-108] `6:33`
MATCH 5
1. [126-132] `:22.34`