-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.

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78
  • 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? – paxdiablo Aug 18 '20 at 06:49
  • Possible duplicate - [Python regular expressions return true/false](https://stackoverflow.com/questions/6576962) – Dishin H Goyani Aug 18 '20 at 07:03
  • @paxdiablo Tbh, I got the expression from another SO post.. – Onur-Andros Ozbek Aug 18 '20 at 07:05

1 Answers1

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

Lukor
  • 1,485
  • 2
  • 14
  • 25