-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
  • 172,331
  • 17
  • 70
  • 167
John L. Godlee
  • 489
  • 4
  • 18
  • 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
  • 2,065
  • 3
  • 20
  • 35
0

With str_extract, also:

stringr::str_extract(vec, "\\bimportant\\d+")
# "important1" "important2" NA           "important3"
acylam
  • 17,372
  • 5
  • 30
  • 43