Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search special pattern in string: R

Tags:

regex

r

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.

string <- "1101000010101111001110"

This is the closest I'm able to do:

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

Expected output:

5
like image 832
and-bri Avatar asked Jan 05 '23 06:01

and-bri


1 Answers

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

(?=...) 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 $&.

length(gregexpr("(?=10+1)", string, perl=TRUE)[[1]])
like image 122
m0nhawk Avatar answered Jan 07 '23 18:01

m0nhawk