user3348051
user3348051

Reputation:

How do I match the domain names with regex by omitting sub-domains?

This is my regex

[a-zA-Z0-9][a-zA-Z0-9-]{0,61}\.[A-Za-z0-9]{1,23}

which matches domains correctly

eg: youtube.com, google.com etc

while it fails to match the domain when there is a sub-domain.

eg. www.youtube.com, mail.google.com

How do I alter it to match only the domain but not the sub-domain? I'm a beginner with regular expressions anyway I don't prefer splitting up the string and matching the part, but with regular expressions.

here's the regexr

thanks

Upvotes: 0

Views: 168

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

I have tried to just fix your regex by adding some restrictions for emails:

(?![\d\s.]+\b)\b([0-9a-z-]{2,}\.[0-9a-z-]{2,3}\.[0-9a-z-]{2,3}|[0-9a-z-]{2,}\.[0-9a-z-]{2,3})(?!@)\b

See updated demo

I added a i case-insensitive option to get rid of [A-Z] and just use [a-z].

Upvotes: 0

neuronaut
neuronaut

Reputation: 2709

I think if you anchor your regex to the end of the input string it will do what you want. To do this, use a $ at the end of the expression:

[a-zA-Z0-9][a-zA-Z0-9-]{0,61}\.[A-Za-z0-9]{1,23}$

This will then match the "goole.com" portion "mail.google.com" as well as strings without a subdomain like "google.com".

Upvotes: 1

Related Questions