0

I have 3 URL scenarios

  1. normal urls:
  2. url with context variable:
  3. whole url is context variable:
    • {$varContext.getProductUrl}

I have to validate input URL to match above 3 scenarios.

I have written regex but which is not working for all scenarios.

^((?:http(s){0,1}://[\\w\\-\\.:/\$\{\}=\?&]+)|(?:\{\$[a-zA-Z]+\.[a-zA-Z]+\}))$

Could any one please help with this?

2
  • 1
    Show us what you've tried. Commented Dec 8, 2018 at 13:44
  • Do you want to test the literal text: {$varContext.getProductUrl} ? Commented Dec 8, 2018 at 18:30

2 Answers 2

1

Hi you made a very simple mistake. Stopped 1% away from the finish line.

^((?:http(s){0,1}:\/\/[\w\-\.:/\${}=\?&]+)|(?:{\$[a-zA-Z]+.[a-zA-Z]+}))$

is the correct one you just forgot to escape the / to denote (mean) a literal /. Mistake appears right after ^((?:http(s){0,1}:

Next time use a site like Regex101, a site to help you test your regex in case you didn't know.

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

1 Comment

Thanks for the quick answer.
0

Apart from escaping the forward slashes after http://, you are escaping the backslash in the character class. \\w would match a backslash and a w. This part \\-\\ would match a range from \ till \ which would match a backslash.

That would match for example http://w\.:/${}=?&

As an addition, you could make a few adjustments to your regex.

  • (s){0,1} can be written as https?
  • The character class [\\w\\-\\.:/\$\{\}=\?&] can be written as [\w.:/${}=?&-] without the escaping of .$? and the hyphen can be moved to the beginning or at the end. \\ would match a backslash.
  • If you don't need the capturing group () you could omit that and only use an alternation |
  • You could use the /i to get a case insensitive match and the character class would become [a-z]
  • Escape the dot \. to match it literally

For example:

const regex = /^https?:\/\/[\w.:/${}=?&-]+|{\$[a-z]+\.[a-z]+}$/i;

See the Regex demo

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.