python-3.xregexipphishing

How to check a part of string with regex pattern in python


I want to check if a string contains some part that matches a given regex pattern. My regex is to check for the presence of an IP address, it goes like this

regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$'''

I want to check if a string like this contains an IP address in it

url_string = "http://110.234.52.124/paypal.ca/index.html"

since it has an IP address, I want to detect that, how can I do that?


Solution

  • import re
    
    regex = "(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( \
                25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( \
                25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( \
                25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)"
    
    result = re.search(regex, "http://110.234.52.124/paypal.com")
    

    you just need remove ^ and $ and call this function if result is None that means not found