Search code examples
rregextidyversedata-cleaningstringr

How to move characters inside brackets to another part of a string?


I'm trying to detect characters of a string which are inside brackets and take those exact characters and replace them into a different string. These are in multiple columns, ref1:ref4.

eg. The values in the columns that are:

"Ref Other Spot (Long Line)"
"Ref Other Spot (Short)"
"Ref Other Spot (Terrier Join)"

and change these to:

"Ref to Long Line"
"Ref to Short"
"Ref to Terrier Join"

I'm using mutate(across()) in this way to try and replace them:

mutate(across(ref1:ref4,
~ str_replace_all(.x, "Ref Other Spot ([.])", paste0("Ref to [.]"))))

But this isn't picking up the "Long Line", "Short" etc. I think my regular expression is missing something (pattern [.])
I'm also not sure if it will be able to both detect then paste the same word back into the expression.

Any help appreciated!


Solution

  • You can use

    str_replace_all(.x, "(Ref)\\s+Other\\s+Spot\\s*\\(([^()]*)\\)", "\\1 to \\2")
    

    See the regex demo.

    Details:

    • (Ref) - Ref string captured into Group 1 (\1)
    • \s+ - one or more whitespaces
    • Other\s+Spot - Other Spot with any one or more whitespaces between the two words
    • \s* - zero or more whitespaces
    • \( - a ( char
    • ([^()]*) - Group 2 (\2): zero or more chars other than parentheses
    • \) - a ) char.