1

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.

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.