Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contents of a RegExp match

I've been trying to convert the following from Python to node.js. It's a simply program that uses regex to check if an IP address is Public or Private:

import re

def is_private_ip(ip):
    """
    Returns `True` if the `ip` parameter is a private network address.
    """
    c = re.compile('(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)')
    if c.match(ip): return True
    return False

print is_private_ip('192.168.0.1') # True
print is_private_ip('8.8.8.8') # False
print is_private_ip('109.231.231.221') # False

I implemented it in Javascript like this:

var localIp = new RegExp(/(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/);
console.log('192.168.0.1'.match(localIp));
console.log('8.8.8.8'.match(localIp));
console.log('109.231.231.221'.match(localIp));

Which gives me the following output:

[ '192.168.',
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  '192.168.',
  index: 0,
  input: '192.168.0.1' ]
null
null

It seems to me like it works (not even sure tbh). The two IPs that should be public are returning null so I'm guessing that's right. I don't understand the output of the other match though? I've not been able to find out what it means

like image 500
Juicy Avatar asked Jan 14 '16 11:01

Juicy


1 Answers

var localIp = new RegExp(/(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/);

console.log('192.168.0.1'.match(localIp));

gives you the output:

[ '192.168.',
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  '192.168.']

That means:

  • '192.168.' that is the match of the regex on this string. the only one
  • undefined is the match for the first group in your regex: (^127\.0\.0\.1)
  • undefined for the group: (^10\.)
  • undefined for the group: (^172\.1[6-9]\.)
  • undefined for the group: (^172\.2[0-9]\.)
  • undefined for the group: (^172\.3[0-1]\.)
  • '192.168.' for the group: (^192\.168\.)

thats because of the parenthesis, each one of them giving a match (or undefined), plus the match that the match() function returns.

like image 86
Salvatorelab Avatar answered Sep 30 '22 10:09

Salvatorelab