R regex may replace the opening bracket but not close the bracket

I am trying to replace the opening and closing brackets in a string. R seems to do this to open the bracket:

> gsub("[\\[]","==","hello [world]")
[1] "hello ==world]"

but not for closing brackets

> gsub("[\\]]","==","hello [world]")
[1] "hello [world]"

Why is this so?

+4
source share
3 answers

See template gsub("[\\]]","==","hello\\] [world]"), [\]]effectively matches \and then ]. Try gsub("[\\]]","==","hello\\] [world]")it and the result will be hello== [world], a literal backslash will be replaced.

In the regular expression pattern, TRE a \inside the parenthesis expression matches a literal backslash.

"[\\]]" \ :

gsub("[[]","==","hello [world]")

- R.

PCRE, , PCRE :

gsub("[\\[]","==","hello [world]", perl=TRUE)

[, ], ][ :

 gsub("[][]","==","hello [world]")
+2

:

gsub("]", "==","hello [world]")
#"hello [world=="
+1

Perhaps a more readable / direct way to do this with stringi,

library(stringi)
stri_replace_all_regex('hello [world]', '\\[|]', '==')
#[1] "hello ==world=="
+1
source

Source: https://habr.com/ru/post/1656767/


All Articles