-3
tekst= "asdadsasdas 192.168.1.1 asdasdadasdasd 10.22.10.5asfasfaff 172.10.5.1safafa"
import re
szukane = r'\d{1,3}.+'
znalezione = re.search(szukane, tekst)

if znalezione:
    co= znalezione.group()
    print(co)

I'm looking to extract the IP address but after running the above code I get:

192.168.1.1 asdasdadasdasd 10.22.10.5asfasfaff 172.10.5.1safafa

Why Is it not working, what should I change?

glls
  • 2,325
  • 1
  • 22
  • 39
Radek Z
  • 11
  • 1
  • 2
  • What do you want to get from string above exactly? – Shafizadeh May 23 '16 at 23:01
  • 2
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. In particular, you need to tell us just what you expect to get. Obviously, the first one is an IP address. Do the last two items contain IP addresses, or not? What happened when you searched for an IP address regexp on line? – Prune May 23 '16 at 23:02
  • Duplicate of several items, including [this](http://stackoverflow.com/questions/2890896/extract-ip-address-from-an-html-string-python). I already voted to close as "unclear", so I'll leave the more accurate closures to the rest of you. – Prune May 23 '16 at 23:07

2 Answers2

5

. is not a literal period in regex. It represents all characters. You'll need to escape it with a backslash. Also, don't forget to include the last group of digits that is not followed by a period.

szukane = r'(?:\d{1,3}\.)+(?:\d{1,3})'

Result:

>>> re.findall(r'(?:\d{1,3}\.)+(?:\d{1,3})', "asdadsasdas 192.168.1.1 asdasdadasdasd 10.22.10.5asfasfaff 172.10.5.1safafa")
['192.168.1.1', '10.22.10.5', '172.10.5.1']
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

Here, let me search that for you ...

aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)

You have to escape the periods ... among other things.

Prune
  • 76,765
  • 14
  • 60
  • 81