const regex = /\b(?:(?:0?[0-9]?[0-9]|1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.??\b){4}/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\b(?:(?:0?[0-9]?[0-9]|1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.??\\b){4}', 'gm')
const str = `Should Match:
204.131.100.104
255.255.005.055
192.168.10.1
172.16.1.1
10.10.10.1
1.2.3.4
255.255.255.255
001.02.3.004
123.145.254.189:8080
1.2.3.4-4.3.20.1
4.3.2.1.9.8.7.6
Shouldnt match:
255.256.255.255
172.999.2.3
this is a string1.2.3.4
this is another 1.2.3.4string
144.109.279.255
v1.2.3.4
`;
// 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