count the number of occurrences of "(" in a string

NPHARD picture NPHARD · Feb 22, 2017 · Viewed 14.7k times · Source

I am trying to get the number of open brackets in a character string in R. I am using the str_count function from the stringr package

s<- "(hi),(bye),(hi)"
str_count(s,"(")

Error in stri_count_regex(string, pattern, opts_regex = attr(pattern, : ` Incorrectly nested parentheses in regexp pattern. (U_REGEX_MISMATCHED_PAREN)

I am hoping to get 3 for this example

Answer

sebastian-c picture sebastian-c · Feb 22, 2017

( is a special character. You need to escape it:

str_count(s,"\\(")
# [1] 3

Alternatively, given that you're using stringr, you can use the coll function:

str_count(s,coll("("))
# [1] 3