【问题标题】:count the number of occurrences of "(" in a string计算字符串中“(”的出现次数
【发布时间】:2017-02-22 14:37:20
【问题描述】:

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

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

stri_count_regex 中的错误(字符串,模式,opts_regex = attr(模式, : ` 正则表达式模式中的括号嵌套不正确。 (U_REGEX_MISMATCHED_PAREN)

我希望在这个例子中得到 3 个

【问题讨论】:

  • 转义str_count(s,"\\(")

标签: r stringr


【解决方案1】:

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

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

或者,如果您使用的是stringr,您可以使用coll 函数:

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

【讨论】:

    【解决方案2】:

    您还可以在基础 R 中使用 gregexprlength

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

    gregexpr 接受一个字符向量并返回一个包含每个匹配项的起始位置的列表。我添加了 fixed=TRUE 以匹配文字。length 将不起作用,因为 gregexpr 在未找到子表达式时返回 -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
    

    【讨论】:

      【解决方案3】:

      如果您想在基数 R 中执行此操作,您可以拆分为单个字符的向量并直接计算 "("(不将其表示为正则表达式):

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

      【讨论】:

      • 或者这个 nchar(s) - nchar(gsub('\\(', '', s)) 用于基础 R
      猜你喜欢
      • 2014-04-24
      • 1970-01-01
      • 2012-06-24
      • 2020-02-21
      • 2012-02-12
      • 2023-02-04
      相关资源
      最近更新 更多