-2

I would like to replace the string ABCDE by FGHIJ only when within a curly bracket. For example the text blabla ABCDE blabla {blabla ABCDE blabla}{ round 235 blabla ABCDE blabla} should be transformed into blabla ABCDE blabla {blabla FGHIJ blabla}{ round 235 blabla FGHIJ blabla} after replacement.

How to achieve this in R using the function gsub()?

Dave2e
  • 15,736
  • 17
  • 32
  • 37

1 Answers1

0

Here is a possible solution:

gsub("(\\{.*)ABCDE(.*?\\})", "\\1FGHIJ\\2", text)
# { } are special regex characters so they need to be escaped with \\
# (\\{.*) - look for a group starting with { followed by one or more characters
# Followed by ABCDE
# Then followed by another group of one or more characters but not greedy (?) ending with }
# The replacement is the first group, FGHIJ and the second group
Dave2e
  • 15,736
  • 17
  • 32
  • 37