-3

I am interested to create a function in which it returns true if the string contains IP address using python.

def having_IP_Adress(URL):
    URL.match('^(http|https)://\d+\.\d+\.\d+\.\d+\.*')
print (having_IP_Adress("http://197.248.5.23/"))

but it gives me an error

Omar Sameh
  • 11
  • 2
  • Please also post the error message. It will help when explaining and guiding you to the fixed solution – hc_dev Aug 31 '20 at 16:45
  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). We expect you to research the topic before posting here. There are many posted solutions (depending on the level of accuracy you need) for detecting valid IP addresses. For an error message, we need the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Prune Aug 31 '20 at 16:55

2 Answers2

0

You can use the re module for regex:

import re

def having_IP_Adress(URL):
    match = re.search(r'^(http|https)://\d+\.\d+\.\d+\.\d+', URL)
    if match is not None:
        return True
    else:
        return False

print(having_IP_Adress("http://197.248.5.23/"))

This returns None if no match was found, so you can easily use that to check

snatchysquid
  • 1,283
  • 9
  • 24
  • 1
    You'll want to use a raw string `r'...'` for the regex, or double all the backslashes. But the last backslash is also wrong. – tripleee Aug 31 '20 at 16:44
  • @tripleee thank you, edited. any other suggestions? – snatchysquid Aug 31 '20 at 16:47
  • Maybe to not attempt to answer poorly articulated questions; too often it turns out the OP means something else, or doesn't understand your answer, or simply never comes back. But let's see. – tripleee Aug 31 '20 at 16:51
0

Compiling the regex once before may even improve performance.

The validation of URLs is covered largely in Stackoverflow. Following snippet is inspired by Django's code:

import re

def is_valid_ip(url):
   regex = re.compile(
    r'^https?://' # http:// or https://
    r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ip, not checked for valid ranges (0..255)!
    r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    return url is not None and regex.search(url)

see answers of How do you validate a URL with a regular expression in Python?

hc_dev
  • 8,389
  • 1
  • 26
  • 38