Improved Regular Expression for Matching URLs
When attempting to detect and parse URLs from user input, it's crucial to use an effective regular expression. In your case, while your current expression captures some URL formats, it fails to account for URLs that lack an explicit protocol scheme, such as www.google.com.
Revised Regular Expression
To address this issue and ensure comprehensive URL matching, consider using the following revised regular expression:
^(?=\S{1,255}$)(https?://)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)
Anatomy of the Regex
This revised regular expression is less restrictive and will successfully match URLs like www.google.com, as well as those with explicit protocols (e.g., http://www.stackoverflow.com).
Example Implementation (JavaScript)
const regex = new RegExp(/(?=\S{1,255}$)(https?://)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)g); const url = 'www.google.com'; if (url.match(regex)) { console.log("URL successfully matched."); } else { console.log("URL did not match."); }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3