Reputation: 133
I have text and patterns.
text <- "It is only a very poor quality car that can give big problems with automatic gearbox"
patterns <- c("very poor","big problems")
Split text
unlist(strsplit(text, "(\\s+)|(?!')(?=[[:punct:]])", perl = TRUE))
Output:
[1] "It" "is" "only" "a" "very" "poor" "quality" "car" "that" "can"
[11] "give" "big" "problems" "with" "automatic" "gearbox"
What I need is match the list of patterns in the sentence instead of "very" "poor" it become "very poor" same with "big problems".
Sample Output:
[1] "It" "is" "only" "a" "very poor" "quality" "car" "that" "can"
[10] "give" "big problems" "with" "automatic" "gearbox"
How should I do this?
Upvotes: 3
Views: 77
Reputation: 12640
This is one approach:
library(stringr)
text <- "It is only a very poor quality car that can give big problems with automatic gearbox"
patterns <- c("very poor","big problems")
patterns_ns <- setNames(str_replace_all(patterns, " ", "&&"), patterns)
text_ns <- str_replace_all(text, patterns_ns)
text_split <- str_replace_all(unlist(str_split(text_ns, "\\s")), "&&", " ")
text_split
I’ve assumed that "&&"
is a string that doesn’t actually appear in your source text, and that you want to split at white space.
Upvotes: 2