Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of occurrences when string contains substring

Tags:

r

I have string like

'abbb'

I need to understand how many times I can find substring 'bb'.

grep('bb','abbb')

returns 1. Therefore, the answer is 2 (a-bb and ab-bb). How can I count number of occurrences the way I need?

like image 379
Lionir Avatar asked Dec 19 '22 19:12

Lionir


1 Answers

You can make the pattern non-consuming with '(?=bb)', as in:

length(gregexpr('(?=bb)', x, perl=TRUE)[[1]])
[1] 2
like image 126
Pierre L Avatar answered May 24 '23 03:05

Pierre L