R: how to use str_replace_all( ) without regular expression

Viewed 246

I have some textual data which contain "[surname]", "[female name]" and "[male name]". For example,

c("I am [female name]. I am ten years old", "My father is [male name][surname]", "I went to school today") 

I hope to delete them for analysis and expect to get

"I am . I am ten years old", "My father is ", "I went to school today"

But when I run the code below, what it returns is broken. I think str_replace_all might recognize the pattern of [ ] as regular expressions, but I am not entirely sure why.

> str_replace_all(c("I am [female name]. I am ten years old", "My father is [male name][surname]", "I went to school today") , "[surname]", '')

[1] "I  [fl ]. I  t y old" "My fth i [l ][]"      "I wt to chool tody"  

Does anyone know how to solve it? Thank you in advance

1 Answers

Use stringi::str_replace_all:

library(stringi)
data <- c("I am [female name]. I am ten years old", "My father is [male name][surname]", "I went to school today") 
remove_us <- c("[female name]","[male name]","[surname]")
stri_replace_all_fixed(data, remove_us, "", vectorize_all=FALSE)

Results

[1] "I am . I am ten years old" "My father is  "            "I went to school today"   

See R proof.

However, it is simpler with gsub:

gsub('\\[[^][]*]', '', data)

See another R proof.

--------------------------------------------------------------------------------
  \[                       '['
--------------------------------------------------------------------------------
  [^][]*                   any character except: ']', '[' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  ]                        ']'
Related