const regex = /\b\w[-.\w]+\.(com|org|net)\b/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\b\\w[-.\\w]+\\.(com|org|net)\\b', 'gm')
const str = `Test strings
hello.com hello1.com 1hello.com hello-1.com hello-hi1.com 1hello-hi.com h3ll0.com
also matches
hello_1.com
---.com
1234.org
-.net
a.net
abc.comical
www.company.com
this is a sentance about net-working.networking is bla bla bla
will not match other domains
hello.co.uk
hello.co
subdomain.hello.com
correctly grabs the domain for
abc.com&foobar
abc.com/foobar
abc.com?foobar`;
// 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