-2

I'm trying to create a Python (2.7) function that will take a string and return true if its input is an ip address, possibly with a slash in the end, but false otherwise. It needs to return a false value if the string is not just an ip address, but an ip address followed by some sort of path. It doesn't matter if the address is a valid IP or not (999.999.999.999 can be considered an ip address for that matter).

eg: "124.131.141.248" - true "124.131.141.248/" - true "124.131.141.248/bla" - false "hello world" - false

I've tried searching for a solution but most solutions include just checking for a valid IP address, disregarding my other needs.

Any help would be appreciated.

Thanks,

Gil
  • 143
  • 2
  • 9

2 Answers2

0

That seems to be working:

import re
def valid_ip(ip):
    if re.match(r'(\d+\.?){4}\\?$', ip):
        return True
    else:
        return False
lch
  • 2,028
  • 2
  • 25
  • 46
0

Quite easy to solve using a simple regex:

import re
pattern = re.compile("\d{3}\.\d{3}\.\d{3}\.\d{3}(\/)?$")
string1 = "124.131.141.248"
string2 = "124.131.141.248/"
string3 = "124.131.141.248/bla"
string4 = "hello world" 
print(pattern.match(string1)!=None) # true
print(pattern.match(string2)!=None) # true
print(pattern.match(string3)!=None) # false
print(pattern.match(string4)!=None) # false

Here a running example.

rakwaht
  • 3,666
  • 3
  • 28
  • 45