# Regex to get the size of capturing group

Update I guess you could go with some absurd Java lookahead recursion simulation that won’t work
or you could use Python to do it ?

``````>>> import regex
>>> rx_1_2 = r"(?m)^(1(?>(?1))*2)\$"
>>>
>>> input = '''
... 111222222
... 11222234
... 1111222
... 111222
... 1122
... 12
... '''
>>> res = regex.findall( rx_1_2, input )
>>> print( res )
['111222', '1122', '12']
``````

That this question was marked a duplicate of a Java simulated recursion
using lookaheads is astoundingly bad judgment on whoever covered this question up by marking it a duplicate. Just plain poor judgment…

It can be done with pythons regex module.
Needs to use recursion.
Done this way because it is really just nested delimiters.

``````1
1
1
2
2
2
``````

`1(?>[^12]++|(?R))*2`

https://regex101.com/r/4Nxtvl/1

``````                         # Recursion
1                       # 1
(?>                     # Atomic group
[^12]++                 # Possesive, not 1 or 2
|                        # or,
(?R)                    # Recurse the regex
)*                      # End cluster, do 0 to many times
2                       # 2
``````

To not allow inner content use `1(?>(?R))*2` https://regex101.com/r/mSUIp0/1

To add boundary conditions, contain the recursion to a group,
then surround it with boundary constructs.

`(?<!\d)(1(?>[^12]++|(?1))*2)(?!\d)`

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

`````` (?<! \d )               # Not a digit behind
(                       # (1 start), Recursion code group
1                       # 1
(?>                     # Atomic group
[^12]++                 # Possesive, not 1 or 2
|                        # or,
(?1)                    # Recurse the regex group 1
)*                      # End cluster, do 0 to many times
2                       # 2
)                       # (1 end)
(?! \d )                # Not a digit ahead
``````

To not allow inner content use `(?<!\d)(1(?>(?1))*2)(?!\d)` https://regex101.com/r/VI6w0Y/1