Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regex that validates a web address and matches an empty string?

Tags:

regex

The current expression validates a web address (HTTP), how do I change it so that an empty string also matches?

(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
like image 361
Peter Morris Avatar asked Aug 31 '25 22:08

Peter Morris


2 Answers

If you want to modify the expression to match either an entirely empty string or a full URL, you will need to use the anchor metacharacters ^ and $ (which match the beginning and end of a line respectively).

^(|https?:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)$

As dirkgently pointed out, you can simplify your match for the protocol a little, so I've included that for you too.

Though, if you are using this expression from within a program or script, it may be simpler for you to use the languages own means of checking if the input is empty.

// in no particular language...
if input.length > 0 then
    if input matches <regex> then
        input is a URL
    else
        input is invalid
else
    input is empty
like image 149
Alex Barrett Avatar answered Sep 03 '25 20:09

Alex Barrett


Put the whole expression in parenthesis and mark it as optional (“?” quantifier, no or one repetition)

((http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)?
like image 33
Gumbo Avatar answered Sep 03 '25 20:09

Gumbo