0

Would it be possible to reduce these patterns into one pattern ?

PRIV_LOC = re.compile("^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
PRIV_24 = re.compile("^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
PRIV_20 = re.compile("^192\.168\.\d{1,3}.\d{1,3}$")
PRIV_16 = re.compile("^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$")


def is_ip_private(ip):
    return PRIV_LOC.match(ip) or PRIV_24.match(ip) or PRIV_20.match(ip) or PRIV_16.match(ip)
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29

1 Answers1

1

You can try this:

re.compile(r"^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}.\d{1,3}|172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3})$")

Or this, to not lose readability much:

re.compile(r"^(" + '|'.join([
    r"127\.\d{1,3}\.\d{1,3}\.\d{1,3}", # PRIV_LOC
    r"10\.\d{1,3}\.\d{1,3}\.\d{1,3}", # PRIV_24
    r"192\.168\.\d{1,3}.\d{1,3}", # PRIV_20
    r"172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}" # PRIV_16
]) + r")$")
Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81