user3755799
user3755799

Reputation:

Regex to match a capture a domain name

Hi i will have URL in following format:

It all must capture and return a domain name as youtube.

I have tried using

(http://|https://)?(www.)(.?*)(.com|.org|.info|.org|.net|.mobi)

but it showing error as regex parsing nested quantifier.

Please help me out

Upvotes: 1

Views: 941

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

You could try the below regex to get the domain name youtube from the above mentioned URL's,

^(?:https?:\/\/)?(?:www\.)?([^.]*)(?=(?:\.com|\.org|\.info|\.net|\.mobi)).*$

DEMO

It ensures that the domain name must be followed by .com or .info or .org or .net or .mobi.

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

(.?*) should be (.*?) - that's the source of your error.

Also, remember to escape the dot unless you want it to match any character.

And since the www. part is optional, you need to add a ? quantifier to that group as well.

Upvotes: 1

zx81
zx81

Reputation: 41848

If you are using a field that you know is in one of these formats, you can retrieve the match from Group 1 using this regex:

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

In VB.NET:

Dim ResultString As String
Try
    ResultString = Regex.Match(SubjectString, "^(?:https?://)?(?:www\.)?([^.]+)", RegexOptions.Multiline).Groups(1).Value
Catch ex As ArgumentException
    'Syntax error in the regular expression
End Try

Upvotes: 2

Related Questions