0

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.