Extract text between brakets ()

Hi All,

I really strangle to simply extract text between brakets, ().
I have a tibble with 1 column where the values are character chain. And I want to just extract/keep the characters between brakets. I have been reading/trying a lot and sometimes it doesn't work as some examples works only on vectors... not very clear...
Basically, my variable contains values like: ' Country name is (FR)' and I want to create another variable that would have the result: 'FR' ....
Any help, please

You can try regular expressions, like below:

fake_variable <- ' Country name is (FR)'
modified_fake_variable <- stringr::str_extract(string = fake_variable,
                                               pattern = "(?<=\\().*(?=\\))")
modified_fake_variable
#> [1] "FR"

Created on 2019-10-29 by the reprex package (v0.3.0)

Hi Yarnabrina, may I ask why do we use string ?

Sorry, I understood now stringr:: means to use the package stringr
and the string= is the name of the fonction parameter... Ahhu ... Thanks sorry for posting these questions :upside_down_face:

May I ask how did you build the pattern?

Break the pattern in my post above in three parts:

  1. (?<=\\()
  2. .*
  3. (?=\\))

The second part is straightforward. It matches zero or more number of any character in between the opening and closing brackets.

The first part (and the third part) uses positive look behind (and positive look ahead). What they does is that it checks whether the pattern after ?<= (and ?=) and with a pair of parentheses is present or not. If present, it returns the part that matches the pattern given after (and before) this, but not the part that matches itself.

So, basically:

  1. first part checks whether it starts with an opening bracket
  2. second part matched any part within opening and closing bracket
  3. third part checks whether it ends with a closing bracket

I'm not really very experienced with regular expressions, so it can be done easily and my solution and/or explanation may not be accurate. You can check this site.

Hope this helps.


If your question is answered, will you please consider marking this thread as solved?

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.