2

I've been through every post I could find on the subject and nothing have answered my problem;

This is the code:
output = 'Scan results for BrainS (192.168.43.111) Scan results for Slave (192.168.43.107) Scan results for SlaveSmall (192.168.43.242)' while (True) if output[i].isdigit(): # i has initial value of 15, j=0 f[j]=output[i] j+=1 i+=1 elsif(i == len(output)): break else: i+=1 continue

Print:
>>>f ['1','9','2','1','6','8','4','3','1','1','1','0','0','0']

As you can see I'm trying to extract the IP as it is with dots(in this code I didnt try to extract the dots but only the numbers), I cant figure out how do get the string I want exactly as it is: f = 192.168.43.111

Any suggestions? better commands?

eyal360
  • 33
  • 4
  • 2
    Regex is the answer: http://stackoverflow.com/questions/10086572/ip-address-validation-in-python-using-regex – zemekeneng Dec 25 '16 at 20:41

2 Answers2

0

For multiple pairs of parenthesis in the string I think it is best to use a regex like so:

import re

output = '''Scan results for BrainS (192.168.43.111) 
            Scan results for Slave (192.168.43.107)
            Scan results for SlaveSmall (192.168.43.242)'''

f = re.findall(r'\(([^()]+)\)',output)
>>>['192.168.43.111', '192.168.43.107', '192.168.43.242']

Try it here!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • wow thanks a lot works like a charm,how about if there were several lines like this one? but different IP's. then i'd have a few "(" & ")" , is there a solution to that? – eyal360 Dec 25 '16 at 20:45
  • Edit your question to show these other lines. The above code only works if there is only one pair of parenthesis in the string. – Sash Sinha Dec 25 '16 at 20:52
  • I've just edited it, I've added the actual output I get, I tried to simplify it before. I hope this can help you understand my question better. – eyal360 Dec 25 '16 at 21:00
  • That should work @eyal360 , the earlier answer only makes sense for one pair of parenthesis :) – Sash Sinha Dec 25 '16 at 21:11
0

Here you go, this code will do the job!

output = 'My computer IP is = (192.168.43.111) and yours not.'
ip=[]
ip_flag = False

for x in output:
    if x == '(':
        ip_flag = True
        continue
    if ip_flag:
        if x != ')':
            if x != '.': # remove this line of you want the dots
                ip.append(x)
        else:
            break
print(ip)
theIp="" 
for i in ip: 
    theIp+=i
Amjad
  • 3,110
  • 2
  • 20
  • 19
  • 1
    This answer actually gave me the ['1','9','2',...] formation that I didnt want in the first place, but it works good. – eyal360 Dec 25 '16 at 20:56
  • 1
    @eyal360 if you want the dots remove this line `if x != '.':` if you want a string just add a loop at the end like this `theIp="" for i in ip: theIp+=i` done – Amjad Dec 25 '16 at 21:01
  • 1
    you can't see it because im under 15 Rep , but you got it, its just not shown. [link]https://s30.postimg.org/8ci2mzhfl/Upvote.jpg – eyal360 Dec 25 '16 at 22:27