-1

I have a vector:

vec <- c("some text (important1)", "some text, (important2 (unimportant))",
"some text", "some text (unimportant) (important3)")

How can I use grep() to extract only the important text, e.g.:

c("important1", "important2", NA, "important3")
Ed Morton
  • 157,421
  • 15
  • 62
  • 152
John L. Godlee
  • 419
  • 4
  • 16
  • 2
    First, please take a few minutes to …read the [Regex wiki](http://stackoverflow.com/tags/regex/info) and [What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) …search [the most frequently-asked Regex questions on Stack Overflow](http://stackoverflow.com/questions/tagged/regex?sort=frequent) …search [Regular-Expressions.info](http://www.regular-expressions.info/) for details on your specific regex engine …and use [regex101.com](https://www.regex101.com/) for explaining and debugging regexp. Then, explain your question in detail. – wp78de Jul 19 '18 at 18:51
  • 1
    Regular expression questions get better answers if they… show the pattern that isn't working, provide some examples of input text that should match, **and also** ones that shouldn't match. Describe the desired results, and how the pattern isn't producing them. – wp78de Jul 19 '18 at 18:52

2 Answers2

1

Use stringr library and functions str_extract

library(stringr)
str_extract(vec,paste(c("important1","important2","important3"),collapse="|"))

Resulting in

"important1" "important2" NA           "important3"

if you think you'll have others "important4","important5" etc etc

n<-10
to_match=collapse(paste("important",seq(1,n,by=1),sep=""),"|")   
str_extract(vec,to_match)
Marco Fumagalli
  • 1,703
  • 2
  • 16
  • 27
0

With str_extract, also:

stringr::str_extract(vec, "\\bimportant\\d+")
# "important1" "important2" NA           "important3"
acylam
  • 16,587
  • 5
  • 27
  • 40