If the first thing in a character class (inside []) is a square bracket (either one) then it is interpreted literally rather than as part of the character class. This means that you can use [[]
to match a single opening square bracket and []]
to match the closing one. You can even add things after the bracket (but if you want to match both then it is best to use [][]
.
some examples:
> tmp <- c('hello','[',']','[]', '[a-z]')
> grep( '[[]', tmp)
[1] 2 4 5
> grep( '[]]', tmp)
[1] 3 4 5
> grep( '[[].*[]]', tmp)
[1] 4 5
> grep( '[[]az-]', tmp)
integer(0)
> grep( '[[]]', tmp)
[1] 4
> grep( '[][]', tmp)
[1] 2 3 4 5
> grep( '[][az-]', tmp)
[1] 2 3 4 5
> regexpr( '[][az-]*', tmp)
[1] 1 1 1 1 1
attr(,"match.length")
[1] 0 1 1 2 5
attr(,"useBytes")
[1] TRUE