galba84
galba84

Reputation: 112

Regex custom url validator

I need a custom validator for urls with 2 conditions: first condition - it starst with http(s):// second condition the left part of url, before first single slash (or till the end of line if single slash not detected) should NOT contain whitespace, but after slash (if such exist), whitespace should be allowed example:

prohibited url:

  1. https://www.exam ple.com/
  2. htt ps://www.example.com/

allowed url:

  1. https://www.example.com/exam ple
  2. http://www.example.com

I wrote Regex expression ^(?:http(s)?:\/\/)[\S]+\/? but it fails with url in example 1.

Upvotes: 1

Views: 66

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

The \S matches a non whitespace char including a / so in the first example it will not cross the first whitespace but you get a partial match because there is no ending anchor $

One option is to match not a forward slash using a negated character class [^/\s]+ matching not a whitespace char or /. Then optionally match a forward slash and use .* to match the rest of the string.

^https?://[^/\s]+(?:/.*)?$

Regex demo

Upvotes: 1

Related Questions