统计字符串中“(”出现的次数

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

我正在尝试获取 R 中字符串中左括号的数量。我正在使用 stringr 程序包

中的 str_count 函数
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)

这个例子我希望得到 3

( 是一个特殊字符。你需要逃避它:

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

或者,假设您正在使用 stringr,您可以使用 coll 函数:

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

如果你想在 base R 中这样做,你可以拆分成单个字符的向量并直接计算 "("(不将其表示为正则表达式):

> s<- "(hi),(bye),(hi)"
> chars <- unlist(strsplit(s,""))
> length(chars[chars == "("])
[1] 3

您还可以在基数 R:

中使用 gregexprlength
sum(gregexpr("(", s, fixed=TRUE)[[1]] > 0)
[1] 3

gregexpr 接受一个字符向量和 returns 一个包含每个匹配项起始位置的列表。我添加了 fixed=TRUE 以匹配文字。length 将不起作用,因为 gregexpr returns -1 当未找到子表达式时。


如果您有一个长度大于 1 的字符向量,则需要将结果提供给 sapply:

# new example
s<- c("(hi),(bye),(hi)", "this (that) other", "what")
sapply((gregexpr("(", s, fixed=TRUE)), function(i) sum(i > 0))
[1] 3 1 0