I need to find all the groups in a String having consecutive sequence of 0's enclosed between 1
100001abc101 // 2 groups `100001` and `101`
1001ab010abc01001 // 2 groups `1001' and `1001`
1001010001 // 3 groups `1001`, `101` and `10001` --> This is a special case
My Regex for the same is: 1(0+)1 this is working good for 1st and 2nd case but in 3rd test case It's only matching 1001 and 10001 not 101
Please suggest what I am missing.
The problem is match starts from the next character of last matched group, it should start from the same matched character itself.
To match overlapping matches, you should be using a capturing group inside a lookahead like this:
(?=(10+1))
RegEx Demo
Since we are only asserting matches instead of matching them, regex engine is able to return all possible combinations of 10+1 even if they are overlapping.
Try a look-behind and look-ahead instead, since you don't actually want to match the 1s:
/(?<=1)0+(?=1)/
https://regex101.com/r/IGygJj/3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With