-1

I have the following character vector:

text_test <- c(
  "\\name{function_name}",
  "\\title{function_title}",
  "The function \\name{function_name} is used somewhere"
)

I would like to extract the words between curly braces, i.e function_name and function_title. I tried this:

stringr::str_extract(text_test, '\\{[^\\}]*\\}')

but this extracts the curly braces as well.

I have two questions:

  • how can I modify this regex to exclude the curly braces?

  • how can I do that in base R?

bretauv
  • 7,756
  • 2
  • 20
  • 57
  • Does this answer your question? [R : get string between braces { }](https://stackoverflow.com/questions/38560283/r-get-string-between-braces) – Ryszard Czech Feb 22 '21 at 23:54

1 Answers1

1

We can use a regex lookaround to match the { as lookaround followed by one or more characters that are not a }.

stringr::str_extract(text_test, '(?<=\\{)[^\\}]+')
#[1] "function_name"  "function_title" "function_name" 

Regex matches one or more characters that are not a } ([^\\}]+) that follows a { (regex lookaround ((?<=\\{))


In base R, we can use regmatches/regexpr

regmatches(text_test, regexpr("(?<=\\{)[^\\}]+", text_test, perl = TRUE))
#[1] "function_name"  "function_title" "function_name" 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi, could you detail a bit the regex you used? It's quite hard to understand for a novice in regex (like me) – bretauv Dec 01 '20 at 18:19