Jessi Ann George
Jessi Ann George

Reputation: 339

Extracting part of a multi-line string using a regular expression

I am trying to extract the below line from a multi-line string:

eth6.36   Link encap:Ethernet  HWaddr A0:36:9F:5F:24:EE  \r\n          inet addr:36.36.36.10  Bcast:36.36.36.255  Mask:255.255.255.0\r\n          inet6 addr: fe80::a236:9fff:fe5f:24ee/64

When I try to extract just eth6.36 Link encap, I get an error.

test = 'ifconfig eth6.36\r\neth6.36   Link encap:Ethernet  HWaddr A0:36:9F:5F:24:EE  \r\n          inet addr:36.36.36.10  Bcast:36.36.36.255  Mask:255.255.255.0\r\n          inet6 addr: fe80::a236:9fff:fe5f:24ee/64 Scope:Link\r\n          UP BROADCAST MULTICAST  MTU:9000  Metric:1\r\n          RX packets:0 errors:0 dropped:0 overruns:0 frame:0\r\n          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0\r\n          collisions:0 txqueuelen:0 \r\n          RX bytes:0 (0.0 b)  TX bytes:7004 (6.8 KiB)\r\n\r\n'

match = re.match('(eth6.36\sLink encap:)', test)
print match.groups()
...
AttributeError: 'NoneType' object has no attribute 'groups'

Any ideas please?

Upvotes: 2

Views: 145

Answers (3)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14945

Use findall with multiline instead. You also need a quantifier for \s.

>>> re.findall(r'(eth6.36\s+Link encap:)',test, re.M)
['eth6.36   Link encap:']

If you're sure that only one result will come use search and remove the grouping parentheses:

>>> re.search(r'eth6.36\s+Link encap:',test).group()
'eth6.36   Link encap:'

Upvotes: 0

Fabian Fagerholm
Fabian Fagerholm

Reputation: 4139

re.match matches from the beginning of the string. Use re.search instead as it matches anywhere in the string:

>>> match = re.search('(eth6.36\s+Link encap:)', test)
>>> print match.groups()
('eth6.36   Link encap:',)

Also, you have to specify that multiple whitespace characters match: \s+ (note the +).

Upvotes: 1

sameera sy
sameera sy

Reputation: 1718

You want this, There was a mistake in the formation of regex

import re
test = 'ifconfig eth6.36\r\neth6.36   Link encap:Ethernet  HWaddr A0:36:9F:5F:24:EE  \r\n          inet addr:36.36.36.10  Bcast:36.36.36.255  Mask:255.255.255.0\r\n          inet6 addr: fe80::a236:9fff:fe5f:24ee/64 Scope:Link\r\n          UP BROADCAST MULTICAST  MTU:9000  Metric:1\r\n          RX packets:0 errors:0 dropped:0 overruns:0 frame:0\r\n          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0\r\n          collisions:0 txqueuelen:0 \r\n          RX bytes:0 (0.0 b)  TX bytes:7004 (6.8 KiB)\r\n\r\n'

match = re.search('(eth6\.36\s*Link encap:)', test)
print match.groups()

Output

('eth6.36   Link encap:',)

Upvotes: 1

Related Questions