I need a regular expression to validate an absolute URL OR a relative URL.
- http://www.example.com should pass
- /example/some.pdf should pass
- /example.com/some.pdf should fail
- example should fail
I need a regular expression to validate an absolute URL OR a relative URL.
(http://|/)[^ :]+
Also of note, /example.com/some
is a valid url as a folder can have a period in it, and not all files have extensions.
Depending on the system there could easily be more types of characters to add to the negated brackets.
The easiest way to do this would be to actually request the file metadata from the server to check weather it actually exists but that wouldn't use regex at all.
As Konrad Rudolph correctly points out: ALL of the examples in the OP are valid URLs! And did you know that an empty string is also a valid URL? Its true! If you really want to validate a URL, or shall I say URI, the first document to read is: RFC-3986 - Uniform Resource Identifier (URI): Generic Syntax. I have been looking into this issue a bit and have written (am writing) an article on the subject:
Regular Expression URI Validation
Note that this only deals with a generic URI. You will probably want to look into further requirements specific to the schemes you are interested in (i.e. HTTP
), e.g. require that a host name be a vaild DNS host.