0

i want to match the url with contatin http/https and (www) or without (www)with the help of regular expression. following is my regualr expression

^((https?)://)(www\\.)| ^$ +(\.[a-z0-9-]+)+([/?].*)?$

but in this, the empty string is not work for example : when i enter http://www.google.com is valid url but http://google.com is not valid. thanks for the answer in advance.

Harmeet Singh Taara
  • 6,483
  • 20
  • 73
  • 126

1 Answers1

1

You can't search for an not existing part using ^$. that is expecting a start of a string(row), end of the string (row).

Just make the "www" part optional:

^((https?)://)(www\\.)?(\.[a-z0-9-]+)+([/?].*)?$

another problem is, you are searching for two dots in a row:

^((https?)://)(www\\.)?(\.[a-z0-9-]+)+([/?].*)?$
                    ^    ^

I think a better pattern would be

^((https?)://)(www\\.)?([a-z0-9-]+)(\.[a-z0-9-]+)*([/?].*)?$

Are you aware, that you are excluding a lot of valid URLS, by only allowing the characters [a-z0-9-]?

stema
  • 90,351
  • 20
  • 107
  • 135
  • thanks for this , but i want to restricted `(www)` only ,in this the other character also accept like 'sss' – Harmeet Singh Taara Jun 14 '13 at 07:33
  • 1
    How to you want to know to what part of the domain the character sequence belongs? e.g. `http://www.sss.com` versus `http://sss.com`? – stema Jun 14 '13 at 07:38
  • so @stema what i do, or please give me another regular expression , which validate all valid url. – Harmeet Singh Taara Jun 14 '13 at 07:41
  • see [What is the best regular expression to check if a string is a valid URL?](http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url) – stema Jun 14 '13 at 07:44