Home >Web Front-end >JS Tutorial >How Can I Efficiently Match URLs Using Regular Expressions?
How to Efficiently Match URLs Using Regular Expressions
Regular expressions provide a powerful way to validate and parse complex strings, including URLs. To ensure accurate URL detection in your input box, consider using these optimized regular expressions:
Regex for URLs with HTTP/HTTPS Protocol:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Regex for URLs without Protocol Requirement:
[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
JavaScript Implementation Example:
const regex = new RegExp(expression); const t = 'www.google.com'; if (t.match(regex)) { alert("Successful match"); } else { alert("No match"); }
These regular expressions will accurately detect URLs, regardless of whether they start with "http" or "https". They are less restrictive than your current regex, allowing you to parse URLs in various formats without issues. By adhering to these regex patterns, you can enhance the efficiency and accuracy of your URL parsing functionality.
The above is the detailed content of How Can I Efficiently Match URLs Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!