How to extract IPs from a given string

skumar_srbh
Tera Guru

Hi Team...

I have a case where, expected to extract all the IP addresses from a given input.  I did use few regex , but it does not work completely. could anyone please suggest a valid regex which will work for the below scenarios as well.. 

i/p  -

"This 1.1.1.1 is an input2.2.2.2,to extract all the IP address [3.3.3.3], which 44.4.4.4regex should be used 3.3.3.P to extract all the valid IP address."

 

expected  o/p - 1.1.1.1 ,  2.2.2.2, 3.3.3.3 , 44.4.4.4

 

Thanks in advance for the help!!!

Kumar

4 REPLIES 4

RaghavSh
Kilo Patron

What will be an expected input? can you share that. There should be some common pattern to extract the same.


Raghav
MVP 2023

sample input

"This 1.1.1.1 is an input2.2.2.2,to extract all the IP address [3.3.3.3], which 44.4.4.4regex should be used 3.3.3.P to extract all the valid IP address."

@skumar_srbh we usually do string manipulations to get substring but in your case it does not follow any pattern.


Raghav
MVP 2023

Appli
Mega Sage
Mega Sage

Hi, please try this regex

var str1 = "This 1.1.1.1 is an input2.2.2.2,to extract all the IP address [3.3.3.3], which 44.4.4.4regex should be used 3.3.3.P to extract all the valid IP address.;";
var str2 = str1.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/g).join(", ");
gs.info('The list of IP addresses: '+str2);
Hope it helps