0
library(tidyverse)
df <- data.frame(col1 = c("one space", "two  (spaces)"))
#>            col1
#> 1     one space
#> 2 two  (spaces)

When I try and replace the phrase two (spaces) with ts I come up short:

# Try #1
df %>% mutate(col1 = gsub("two  (spaces)", "ts", col1))
#>            col1
#> 1     one space
#> 2 two  (spaces)

# Try #2
df %>% mutate(col1 = gsub("two[:space:][:space:](spaces)", "ts", col1))
#>            col1
#> 1     one space
#> 2 two  (spaces)

How do I do this properly?

In the first attempt R Studio always changes my two spaces into one tab basically. I'm not sure if that's the issue. My second attempt feels like it should work. Unfortunately, it appears R does not care for my feelings.

Display name
  • 4,153
  • 5
  • 27
  • 75
  • 1
    `df %>% mutate(col1 = gsub("two (spaces)", "ts", col1, fixed = TRUE))` in case anybody sees this in the future. – Display name Apr 17 '20 at 21:02
  • 1
    If you wish to replace any string surrounded by double quotes that contains a left parenthesis you could obtain matches of the regex `(?<=")[^("]*\([^"]*(?=\")`. [Demo](https://regex101.com/r/WKAusP/1/) – Cary Swoveland Apr 17 '20 at 22:37

0 Answers0