我的数据如下:
t <- "The data is like hi hi hi hi and hi hi end"
我的正则表达式是:
grammer <- "[[:space:]]*(hi)+[[:space:]]"
执行以下两行后:
res <- gregexpr(grammer, t)
regmatches(t, res)
我得到了输出:
[[1]]
[1] " hi " "hi " "hi " "hi " " hi " "hi "
但是,我想要类似:" hi hi hi hi "
和" hi hi "
答案 0 :(得分:4)
你可以这样做,
> t<-"The data is like hi hi hi hi and hi hi end"
> grammer<-"[[:space:]]*(hi[[:space:]])+[[:space:]]*"
> res<-gregexpr(grammer, t)
> regmatches(t, res)
[[1]]
[1] " hi hi hi hi " " hi hi "
OR
> grammer<-"[[:space:]]*(hi[[:space:]])+"
> res<-gregexpr(grammer, t)
> regmatches(t, res)
[[1]]
[1] " hi hi hi hi " " hi hi "
OR
> t <- "The data is like hi hi hi hi and hi hi end hi"
> grammer<-"[[:space:]]*(hi\\>[[:space:]]?)+"
> res<-gregexpr(grammer, t)
> regmatches(t, res)
[[1]]
[1] " hi hi hi hi " " hi hi " " hi"
没有前导或后续空格。
> t <- "The data is like hi hi hi hi and hi hi end hi"
> grammer<-"hi\\>([[:space:]]hi)*"
> res<-gregexpr(grammer, t)
> regmatches(t, res)
[[1]]
[1] "hi hi hi hi" "hi hi" "hi"
<强>解释强>
[[:space:]]*
匹配空格字符零次或多次。(hi[[:space:]])+
匹配字符串hi
和以下空格一次或多次。