从R中的文本中提取模式

时间:2014-10-15 09:31:15

标签: regex r

我的数据如下:

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 "

1 个答案:

答案 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和以下空格一次或多次。