计数字符串内的模式

有固定的模式

stri_count_fixed("babab", "b")
# [1] 3
stri_count_fixed("babab", "ba")
# [1] 2
stri_count_fixed("babab", "bab")
# [1] 1

本地:

length(gregexpr("b","babab")[[1]])
# [1] 3
length(gregexpr("ba","babab")[[1]])
# [1] 2
length(gregexpr("bab","babab")[[1]])
# [1] 1

函数在字符串和模式上进行矢量化:

stri_count_fixed("babab", c("b","ba"))
# [1] 3 2
stri_count_fixed(c("babab","bbb","bca","abc"), c("b","ba"))
# [1] 3 0 1 0

基础 R 解决方案

sapply(c("b","ba"),function(x)length(gregexpr(x,"babab")[[1]]))
# b ba 
# 3  2

用正则表达式

第一个例子 - 找到 a 和之后的任何字符

第二个例子 - 找到 a 和之后的任何数字

stri_count_regex("a1 b2 a3 b4 aa", "a.")
# [1] 3
stri_count_regex("a1 b2 a3 b4 aa", "a\\d")
# [1] 2