为什么gsub(“ [\\ [\\]]”,“”,字符串)== gsub(“ \\ [| \\]”,“”,字符串)为FALSE?

Using regex we can specify multiple characters inside [...]or with | between them. We can test that like here:

string <- "[abcde]"
gsub("[be]", "", string) == gsub("b|e", "", string)
# TRUE
# both give "[acd]"

If we want to do the same for [ and ] instead of b and e I would simiarly do

gsub("[\\[\\]]","", string) == gsub("\\[|\\]","", string)
# FALSE

Here, only gsub("\\[|\\]","", string) gives the expected "abcde" while gsub("[\\[\\]]","", string) leaves the string unchanged. Why is this?

评论