在字符串中搜索特殊模式:R

时间:2022-09-13 07:44:35

I like to know the number of 0's which are surrounded by 1. But if there are more than one 0 without interrupted by a 1 it count only as one.

我想知道被1包围的0的数量。但是如果有多个0而没有被1中断,它只计为1。

string <- "1101000010101111001110"

This is the closest I'm able to do:

这是我能做的最接近的事情:

length(gregexpr(pattern ="101",string)[[1]])

Expected output:

5

1 个解决方案

#1


9  

With gregexpr you can use lookahead assertion with perl=True to find overlapping matches:

使用gregexpr,你可以使用perl = True的lookahead断言来查找重叠匹配:

(?=...) is a lookahead assertion:

(?= ...)是一个先行断言:

(?=...)

A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

零宽度正向前瞻断言。例如,/ \ w +(?= \ t)/匹配单词后跟选项卡,而不包括$&中的选项卡。

length(gregexpr("(?=10+1)", string, perl=TRUE)[[1]])

#1


9  

With gregexpr you can use lookahead assertion with perl=True to find overlapping matches:

使用gregexpr,你可以使用perl = True的lookahead断言来查找重叠匹配:

(?=...) is a lookahead assertion:

(?= ...)是一个先行断言:

(?=...)

A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

零宽度正向前瞻断言。例如,/ \ w +(?= \ t)/匹配单词后跟选项卡,而不包括$&中的选项卡。

length(gregexpr("(?=10+1)", string, perl=TRUE)[[1]])