Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract ip address from a string using regex

 var r = "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; //http://www.regular-expressions.info/examples.html

var a = "http://www.example.com/landing.aspx?referrer=10.11.12.13";

var t = a.match(r); //Expecting the ip address as a result but gets null

The above is my code to extract ip address from a string. But it fails to do so. Kindly advice where it fails.

like image 220
MARKAND Bhatt Avatar asked Sep 21 '15 07:09

MARKAND Bhatt


People also ask

What is the regex for IP address?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."

What is general expression for extracting IP address from logs?

The regular expression for valid IP addresses is : ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) \.){ 3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)


1 Answers

You have defined r as string, initialize it as regular expression.

var r = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;

var r = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/; //http://www.regular-expressions.info/examples.html

var a = "http://www.example.com/landing.aspx?referrer=10.11.12.13";

var t = a.match(r);
console.log(t[0])
like image 60
Satpal Avatar answered Sep 24 '22 11:09

Satpal