"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?

How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?

Published on 2024-12-20
Browse:936

How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?

Detecting URLs with Regular Expressions

Your current code fails to match naked URLs, which lack the "http://" prefix. To address this, consider adopting a comprehensive regular expression:

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

This enhanced expression includes the following features:

  • It ensures that URLs start with either "http://", "https://", or nothing.
  • It allows for subdomains by including "(www.)" as an optional prefix.
  • It supports domain names up to 256 characters in length and top-level domains up to 6 characters.

For those who do not require the HTTP protocol in their matches, an alternative expression is available:

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

To demonstrate the functionality of these expressions, check out the online testing tools at http://regexr.com?37i6s (for the first expression) or http://regexr.com/3e6m0 (for the less restrictive expression).

Here's an example JavaScript implementation using the more comprehensive regular expression:

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");
}
Latest tutorial More>

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