megazero
megazero

Reputation: 35

python recursive regular expression

I have a message that is

msg = 'untagged ethernet 1 ethernet 2 ethernet 3'

and I want to write a regex that will find the 'ethernet x' pattern so that if i run

m = re.match(str(regex),msg) 
print m.groups()

it will save the variable x and display something like

(1,2,3)

the expression that I have tried is

regex = 'untagged ((?: ethernet (\S+))*)'

but i am getting

('ethernet 1', 'ethernet 1', '1')\

as a result

Upvotes: 0

Views: 501

Answers (1)

user2555451
user2555451

Reputation:

You should use re.findall instead of re.match:

>>> import re
>>> msg = 'untagged ethernet 1 ethernet 2 ethernet 3'
>>> re.findall("ethernet\s\d+", msg)
['ethernet 1', 'ethernet 2', 'ethernet 3']
>>> re.findall("ethernet\s(\d+)", msg)  # Just the numbers
['1', '2', '3']
>>> tuple(map(int, re.findall("ethernet\s(\d+)", msg)))  # What was in your post
(1, 2, 3)
>>>

re.findall was designed explicitly for finding all occurrences of a pattern inside a string.

Upvotes: 4

Related Questions