Reputation: 1013
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)
Upvotes: -1
Views: 882
Reputation: 49640
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
Upvotes: 4