Search for a special pattern in a string: R

I like to know the number 0that is surrounded 1. But if there is more than one 0without interruption 1, it is considered only one.

string <- "1101000010101111001110"

This is the closest I can do:

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

Expected Result:

5
+4
source share
1 answer

With, gregexpryou can use the lookahead statement with perl=Trueto find matching matches:

(?=...)- statement :

(?=...)

Positive feedback statement with zero width. For example, /\w+(?=\t)/matches the word followed by the tab, without including the tab in $&.

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

Source: https://habr.com/ru/post/1673741/


All Articles