-2

I am trying to use regex to see if the given string is an IPv4 address. I want to return a boolean value True/False depending on the string. This is my code:

import re

def isIPv4Address(inputString):
    pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s')
    
    return pattern.match(inputString)

The value is null. At this point, I can tell that the function does not return a boolean value. However, all questions I see about regex and IP addresses is about writing the pattern instead of a full implementation. I know that the actual implementation shouldn't be any longer than this because it just takes the input and compares it against the regex.

3
  • 2
    Provide some sample data that's failing and, please, explain what the \s is doing at the end of your pattern. If it's to make sure there's white space after the IP address, then why not before as well? And what will you do with the perfectly valid "172.16.4.4", with no spaces? Commented Aug 18, 2020 at 6:49
  • Possible duplicate - Python regular expressions return true/false Commented Aug 18, 2020 at 7:03
  • @paxdiablo Tbh, I got the expression from another SO post.. Commented Aug 18, 2020 at 7:05

1 Answer 1

1

match returns the match (a re.Match object) or None if the expression doesn't match. If you want to return a boolean whether the regex matches, you probably want to use pattern.match(inputString) is not None

Sign up to request clarification or add additional context in comments.

2 Comments

The code fails when input is "172.16.254.1". I think my expression is wrong.
@oo92 you have a \s (whitespace) at the end of your expression, which is not in your string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.