0

I use a variable to save an ip like this, but I need to verify that it really has an ip format. The ip field does not always have to be a list. I have this:

ip=["8.8.8.8","8.8.8.6"] # List or only one element
reg_ip = r'(?:\d{1,3}\.)+(?:\d{1,3})'
filter_ip=re.findall(reg_ip,ip)

But the answer is as follows

filter_ip= [u"8.8.8.8",u"8.8.8.6"]

And therefore does not meet the condition

if ip == reg_ip:

How should I do it?

3
  • 1
    Looks like you need re.search() ? Commented Aug 8, 2019 at 12:15
  • if ip in filter_ip Commented Aug 8, 2019 at 12:19
  • Possible duplicate of IP address regex python Commented Aug 12, 2019 at 9:06

2 Answers 2

0
import re
ip="8.8.8.8"
reg_ip = r'(?:\d{1,3}\.)+(?:\d{1,3})'
filter_ip=re.findall(reg_ip,ip)
if ip in reg_ip:
   pass
Sign up to request clarification or add additional context in comments.

2 Comments

Mmm it works, but if the ip field is a list? I have the following. ip=8.8.8.8,8.8.8.6 filter_ip=[u"8.8.8.8", u"18.8.8.6"]
Nice, give to this answer is useful. I will check
0

Basically, you are checking if there any matches with Regex, so .findall will return you the number of matches

import re
ip=["8.8.8.8","8.8.8.6"]
reg_ip = re.compile(r'(?:\d{1,3}\.)+(?:\d{1,3})')
filter_ip = list(filter(reg_ip.search, ip))
if ip == filter_ip:
   print "All ip Matched!"

Recommend you to use .search if you have a single ip to check for as its faster and you need not need multiple matches.

Using .search

ip="8.8.8.8"
reg_ip = r'(?:\d{1,3}\.)+(?:\d{1,3})'
if re.search(reg_ip,ip):
    print "Matched !"

5 Comments

It could be the case that ip was a listing, and therefore filter_ip the same
It does not work, it does not enter the conditional when it is a list. The problem may be the format?
@DaniMartinez i expect it should work fine now. please check and confirm
The ip field does not always have to be a list. I have this error: 'str' object has no attribute 'search'
@DaniMartinez Can you please edit your question with exact sample input and desired output? and the errors which you have. As you have always been changing the question each and every time :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.