Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for any non-empty consecutive sequence of 0's enclosed between 1

Tags:

java

regex

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.

like image 251
Neeraj Jain Avatar asked Dec 07 '25 05:12

Neeraj Jain


2 Answers

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.

like image 127
anubhava Avatar answered Dec 08 '25 19:12

anubhava


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

like image 45
user94559 Avatar answered Dec 08 '25 17:12

user94559