0

Is there a simple way to grep both brackets in a single line of code. I would like to include opening [ and closing ] bracket in a single line of code. I have tried all kinds of combinations but it seems only one at a time is possible. I have the following:

if(grepl("\\[+",CAS)) return(FALSE)
oguz ismail
  • 1
  • 16
  • 47
  • 69
rjss
  • 935
  • 10
  • 23

1 Answers1

4

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
Greg Snow
  • 48,497
  • 6
  • 83
  • 110