Python Regex Removing One Too Many...

Well, I'm a python noob and my last post here I was introduced to Regex. I thought this would be easy since I knew Regex with Bash. However, I've been banging my head a while to extract an ip address from ifconfig with this:

#!/usr/bin/python

import re
import subprocess
from subprocess import Popen, PIPE

pattern = re.compile(r'inet.\S+(\d+\.\d+\.\d+\.\d+)')

p1 = Popen(["/sbin/ifconfig"], stdout=subprocess.PIPE)

output = p1.communicate()[0]
result = re.findall(pattern, output)

print result[1]

Unfortunately I'm getting one too characters cut out. I should get 10.0.0.139 instead of the following:

$ ./saturday.py 
0.0.0.139

Anyone see where I went wrong?

OSX 10.7.5, Python 2.7.3.
Try:-

pattern = re.compile(r'inet.(\S+\d+\.\d+\.\d+\.\d+)')

Actually I did try that before posting. Here's what I get:

$ ./sat.py 
addr:10.0.0.139

No good for me as I'm trying to cut after the semi-colon.

Hi,
Try to replace:

pattern = re.compile(r'inet.\S+(\d+\.\d+\.\d+\.\d+)')

by

pattern = re.compile(r'inet.\D+(\d+\.\d+\.\d+\.\d+)')

Regard.

Actually I ended up getting it with this:

#!/usr/bin/python

import re
import subprocess
from subprocess import Popen, PIPE

pattern = re.compile(r'inet.\S+(\S+\d+\.\d+\.\d+\.\d+)')

p1 = Popen(["/sbin/ifconfig"], stdout=subprocess.PIPE)

output = p1.communicate()[0]
result = re.findall(pattern, output)

print result[1]

Why it works I don't know. If anyone wants to shed some light on that I'm all ears.

Your last solution work because the class '+' catch the most wide possible and so by example:
addr:10.0.0.139
first \S+ for addr:
second \S+ for 1 (here, \S work also)
\d+\.\d+\.\d+\.\d+ for 0.0.0.139

But your solution do not work with if first number is one digit as by exemple:
addr:1.0.0.139

Regards.

1 Like