You can do it,
> 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"
No leading or following spaces.
> 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"
Explanation:
[[:space:]]* Matches a run character zero or more times.(hi[[:space:]])+ Matches the string hi and the next space one or more times.
Avinash raj
source share