1

I am needing to check the url entered on a page and its still matching http:// only string. I want it to fail if user only enters http://

Regex pattern ^(https?:\/\/)(www\.)?(([a-zA-Z]+)?(\.[a-zA-z]{2,6})?)((\d{1,3}\.){3}(\d{1,3}){1})?$/gm

tests:

google.com  <---- fails as it should
https://google.com  <---- Pass
https:google.com  <---- fails as it should
www.cool.com.au  <---- fails as it should
https://asdsds.Com
http://a  <---- Pass
https://  <---- Pass **BUT SHOULD FAIL**
http://10.10.10.00  <---- Pass
http://www.cool.com  <---- Pass
https://123123.asd  <---- fails as it should
http://www.cool.com.au/ersdfs  <---- fails as it should
http://www.cool.com.au/ersdfs?dfd=dfgd@s=1  <---- fails as it should
http://www.cool.com:81/index.html  <---- fails as it should
0

1 Answer 1

2

The main point here is to add (?!$) after ^(https?:\/\/), it will fail the match if there is end of string/line immediately after the protocol part.

You can use

^(?:https?:\/\/)(?!$)(?:www\.)?[a-zA-Z]*(?:\.[a-zA-Z]{2,6})?(?:(?:\d{1,3}\.){3}\d{1,3})?$

See the regex demo.

Note the {1} is redundant and need removing. [a-zA-z] (that does not match only letters) is most probably a typo, you must have meant [a-zA-Z].

I removed unnecessary capturing groups and converted capturing ones into non-capturing to get cleaner regex match structure, only use capturing mechnanism when you need to actually get the match parts.

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.