Reputation: 647
How to capture 1 or 2 digits in a regex?
Text
IF-MIB::ifDescr.1 = 1/1/g1, Office to DMZ
IF-MIB::ifDescr.10 = 1/1/g10, Office to DMZ
Regex
This works for 1 digit only. ie. 1/1/g1 but does not work for 2 digits. ie. 1/1/1g10.
(?P<ifDescr>(?<=ifDescr.\d = ).*)
This works for 2 digits in the regex tester but not in python3 in centos.
(?P<ifDescr>(?<=ifDescr.\d|\d = ).*)
I get the following error:
re.error: look-behind requires fixed-width pattern
Upvotes: 0
Views: 192
Reputation: 20724
Although you can't make a lookbehind non-fixed width, but you can group two lookbehinds with an or condition:
(?:(?<=ifDescr\.\d = )|(?<=ifDescr\.\d\d = ))(?P<ifDescr>.*)
(?:...)
a non-capture group(?<=ifDescr\.\d = )
lookbehind, match ifDescr.
with one digit|
or(?<=ifDescr\.\d\d = )
lookbehind, match ifDescr.
with two digits(?P<ifDescr>.*)
match whatever after it, and set a group back reference called ifDescr
check the proof
But this works for limited combinations. If you're not sure how many digits there are, you should use group captures, and then get the result from group ifDescr
(?:ifDescr\.\d+ = )(?P<ifDescr>.*)
Upvotes: 0