Python regex issue: opt. substring b/w

I am trying to match a packet content with a regex API. The regex should capture the Framed-IP-Address Attribute (client_ip) when it appears in the packet, and should ignore it when it does not appear.

Currently, the regex pattern is enclosed in another capture group (ending with ? meaning 0 or 1 occurrence), but the pattern fails to capture client_ip when it is present.

Example packet content with Framed-IP-Address Attribute present:

IP (tos 0x0, ttl 64, id 35592, offset 0, flags [DF], proto UDP (17), length 213)
    10.10.10.1.41860 > 10.10.10.3.1813: [udp sum ok] RADIUS, length: 185
    Accounting-Request (4), id: 0x0a, Authenticator: 41b3b548c4b7f65fe810544995620308
      Framed-IP-Address Attribute (8), length: 6, Value: 10.10.10.11
        0x0000:  0a0a 0a0b
      User-Name Attribute (1), length: 14, Value: 005056969256
        0x0000:  3030 3530 3536 3936 3932 3536

Example packet content without Framed-IP-Address Attribute present:

IP (tos 0x0, ttl 64, id 60162, offset 0, flags [DF], proto UDP (17), length 163)
    20.20.20.1.54035 > 20.20.20.2.1813: [udp sum ok] RADIUS, length: 135
    Accounting-Request (4), id: 0x01, Authenticator: 219b694bcff639221fa29940e8d2a4b2
      User-Name Attribute (1), length: 14, Value: 005056962f54
        0x0000:  3030 3530 3536 3936 3266 3534

Regex used:

packet_re = (r'.*RADIUS.*\s*Accounting(\s|-)Request.*(Framed(\s|-)IP(\s|-)Address.*Attribute.*Value: (?P<client_ip>\d+\.\d+\.\d+\.\d+))?.*(Username|User-Name)(\s|-)Attribute.*Value:\s*(?P<username>\S+).*')

The issue with the current regex pattern is that the .* before the Framed-IP-Address Attribute capture group is greedy and matches everything before it, including the Accounting-Request part of the packet content. This causes the pattern to fail when Framed-IP-Address Attribute is present in the packet.

To fix this issue, you can make the .* before the Framed-IP-Address Attribute capture group non-greedy by adding a ? after it. This will make it match as few characters as possible before reaching the Framed-IP-Address Attribute part.

Updated regex pattern:

packet_re = (r'.*?RADIUS.*?\s*Accounting(\s|-)Request.*?(Framed(\s|-)IP(\s|-)Address.*?Attribute.*?Value: (?P<client_ip>\d+\.\d+\.\d+\.\d+))?.*?(Username|User-Name)(\s|-)Attribute.*?Value:\s*(?P<username>\S+).*')

With this updated pattern, the client_ip capture group should correctly capture the Framed-IP-Address Attribute when it is present in the packet content, and should ignore it when it is not present.