Seb
Seb

Reputation: 11

Regex to extract .com domains only?

I've got this regex for generic domains but what would I need to alter for it to only extract .com domains?

^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)

Upvotes: 0

Views: 48

Answers (3)

user12127707
user12127707

Reputation: 1

if you just need to know if there is a hit (dont need grouping for replace, etc.) just add

  (\.com) 

to end.

you've got some overkill in there, (must have http(s) 0 or 1 times, must have www. 0 or 1 times)

but it'll do

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42384

You'll want to add .\com to your main grouping.

Ultimatey I believe you're looking for:

^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+\.com)

This can be seen working here:

const regex = /^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+\.com)/;
const sites = [
  'https://www.example.com',
  'https://www.example.org',
  'www.exampe.com',
  'www.example.org'
]

sites.forEach(function(site) {
  console.log(regex.test(site));
})

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 31035

It's kind of difficult to guess your needs but if you want to simply match those ending in .com you can simply add it to the regex like this:

^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)\.com

Working demo

Upvotes: 3

Related Questions