Regular expression for any non-empty sequential sequence 0, enclosed between 1

I need to find all the groups in a string that has a sequential sequence of 0, 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: 1(0+)1

this works well for 1st and 2nd cases, but in 3rd test case only match 1001

and 10001

not101

Please suggest what I am missing.

The problem is that the match starts at the next character of the last matched group, it must start at the same matched character.

+3


source to share


3 answers


To match overlapping matches, you must use a capture group within the view:

(?=(10+1))

      



Demo version of RegEx

Since we only assert matches instead of matching them, the regex engine is able to return all possible combinations 10+1

, even if they overlap.

+2


source


Try searching and looking ahead because you really don't want to match 1s:

/(?<=1)0+(?=1)/

      



https://regex101.com/r/IGygJj/3

+2


source


Use something like (?=(10+1))10+


where group 1 contains the sequence rather than the last one.

https://regex101.com/r/uH5OrS/1

In general, you need to move the position using the latter 10+

.
In this case it is not necessary, but I would not get used to not including him, he will bite you someday.

+1


source







All Articles