Home > Web Front-end > JS Tutorial > How Can I Create Robust Regular Expressions to Match URLs with and without Protocol Prefixes?

How Can I Create Robust Regular Expressions to Match URLs with and without Protocol Prefixes?

Barbara Streisand
Release: 2024-12-24 05:54:17
Original
968 people have browsed it

How Can I Create Robust Regular Expressions to Match URLs with and without Protocol Prefixes?

Matching URLs: A Comprehensive Regular Expression Approach

When extracting URLs from input, it's crucial to have a robust regular expression that can handle various scenarios. In this case, the provided regular expression fails to match URLs without the "http" or "https" protocol prefix. To address this challenge, we propose two alternative regular expressions:

For URLs Requiring an HTTP/HTTPS Protocol:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Copy after login

For URLs Without an HTTP/HTTPS Protocol Requirement:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Copy after login

These regular expressions effectively capture URLs with or without the protocol prefix. For experimental purposes, you can test these expressions at http://regexr.com?37i6s (with protocol prefix) and http://regexr.com/3e6m0 (without protocol prefix).

Below is an example JavaScript implementation:

const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
const regex = new RegExp(expression);
const t = 'www.google.com';

if (t.match(regex)) {
  alert("Successful match");
} else {
  alert("No match");
}
Copy after login

The above is the detailed content of How Can I Create Robust Regular Expressions to Match URLs with and without Protocol Prefixes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template