我正在努力使用正则表达式,因此任何见解都会有所帮助。我有一个这样的列表:
[1] "collected 1 hr total. wind >15 mph." "collected 4 hr total.
wind ~15 mph."
[3] "collected 10 hr total. gusts 5-10 mph." "collected 1 hr total.
breeze at 1mph,"
[5] "collected 2 hrs." [6]
我想要:
[1] > 15 mph
[2] ~15 mph
[3] 5-10 mph
[4] 1mph
[5]
[6]
我想在每一行中拉出风速。您能建议正确的正则表达式吗?如你看到的, a)数字和“ mph”之间可以有可变数量的空格 b)mph之前的数字可以有不同的符号“>”,“ <”,“〜”,也可以是间隔“-”
提前谢谢!
答案 0 :(得分:1)
假设每个字符串最多只有一个匹配项,那么我们可以尝试将sapply
和sub
一起使用:
input <- c("collected 1 hr total. wind >15 mph.",
"collected 4 hr total. wind ~15 mph.",
"collected 10 hr total. gusts 5-10 mph.",
"collected 1 hr total. breeze at 1mph,",
"collected 2 hrs.")
matches <- sapply(input, function(x) {
ifelse(grepl("[>~0-9-]+\\s*mph", x),
sub(".*?([>~0-9-]+\\s*mph).*", "\\1", x),
"")})
names(matches) <- c(1:length(matches))
matches
1 2 3 4 5
">15 mph" "~15 mph" "5-10 mph" "1mph" ""
答案 1 :(得分:1)
带有str_extract
library(stringr)
trimws(str_extract(v1, "[>~]?[0-9- ]+mph"))
#[1] ">15 mph" "~15 mph" "5-10 mph" "1mph" NA
v1 <- c("collected 1 hr total. wind >15 mph.",
"collected 4 hr total. wind ~15 mph.",
"collected 10 hr total. gusts 5-10 mph.",
"collected 1 hr total. breeze at 1mph,",
"collected 2 hrs.")