const regex = /\b((?:(?: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}((?:[0-9])|(?:[1-2][0-9])|(?:3[0-2]))\b)?)|((?:[a-f0-9:]+:+)+(?:[a-f0-9])+(?:\/{1}((?:(?:3[0-2]|[12]?\d)))\b)?)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\b((?:(?: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}((?:[0-9])|(?:[1-2][0-9])|(?:3[0-2]))\\b)?)|((?:[a-f0-9:]+:+)+(?:[a-f0-9])+(?:\\\/{1}((?:(?:3[0-2]|[12]?\\d)))\\b)?)', 'gm')
const str = ` 192.168.1.1 192.168.2.1
192.168.3.1
"192.168.10.1", "192.168.10.257" 10.0.0.1, 8.8.8.8
not_an_ip "192.168.0.1 10.9.9.0
random text here
127.0.0.1
192.168.23.12
2001:db8::
::1234:5678
2001:db8::1234:5678
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468
192.168.3.1/32
10.0.0.0/0
12.10.0.0/24
10.0.0.0/24
10.0.0.0/99
1.1.1.25/23
0.0.0.0/3
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/0
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/9
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/10
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/15
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/22
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/32
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/41
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions