1 March 2024

30 Regex Code Snippets Every Web Developer Should Know

By Ronald Smith

Regular expressions are an awesome tool that you definitely want in your developer toolbox. They allow you to match strings of characters based on some pretty complicated criteria, which can save you so much time when you’re building dynamic websites.

As a web developer, you have different tasks than software developers, but you can still benefit from the same basic code principles. Regex may take some time to wrap your head around at first, but once you get the hang of it, you’ll realize just how incredibly powerful it can be.

The hardest part is figuring out how to write your own regex code and understand the syntax. But don’t worry, I’ve got you covered! I’ve compiled 30 different regex code snippets that you can use in your development projects. The best part is that these snippets can be applied to various programming languages like JavaScript, PHP, or Python. So, let’s dive in!

A regular expression, or regex for short, is a pattern made up of characters that can be searched for within a string. It’s like a secret code that helps you find specific patterns or sequences of characters. For example, you can search for an email address or a phone number in a block of text using regex.

Now, let’s explore one of the regex snippets together. This snippet is used to check the strength of a password. It looks a bit complicated, but I’ll break it down for you:

^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).$

This regex pattern is checking for multiple conditions that make a strong password. Let me explain what each part means:

^ – This denotes the start of the string.

(?=.*[A-Z].*[A-Z]) – This checks if there are at least two uppercase letters.

(?=.*[!@#$&*]) – This checks if there is at least one special character.

(?=.*[0-9].*[0-9]) – This checks if there are at least two digits.

(?=.*[a-z].*[a-z].*[a-z]) – This checks if there are at least three lowercase letters.

. – This matches any character.

$ – This denotes the end of the string.

So, using this regex snippet, you can ensure that passwords meet certain criteria to enhance security.

I hope you find these regex code snippets helpful! They will save you time and effort when working on your projects, no matter which programming language you’re using. Remember, practice makes perfect, so keep experimenting and learning. Happy coding!

When it comes to checking the strength of a password, it’s often a matter of personal opinion, so there’s no one right answer. However, I think this regex snippet is a fantastic starting point if you don’t want to create your own password strength checker from scratch. (Source)

Discover the 15 Best Password Managers for 2023

Explore the top password tools and generators to safeguard your online accounts. Create strong and unique passwords, and keep them secure. Learn more

2. Hexadecimal Color

In the world of web development, hex color codes are everywhere. This regex snippet lets you extract hex code matches from any string for any purpose. (Source)

3. Validate Email Address

/[A-Z0-9._%+-]+@[A-Z0-9-]+.+.[A-Z]/igm

Hey there! Have you ever wondered how to tell if a string is actually an email address? Well, as a developer, it’s a pretty common task! Lucky for you, I’ve got a cool trick up my sleeve. Check out this awesome link from SitePoint that offers two different code snippets for checking if a string matches the format of an email address. Pretty neat, huh? (Source)

4. IPv4 Address

/\b(?:(?:25[0-5] |2[0-4][0-9] |[01]?[0-9][0-9]?)\.) (?:25[0-5] |2[0-4][0-9] |[01]?[0-9][0-9]?)\b/

Did you know that an IP address is just like an email address for identifying a specific computer on the Internet? It’s true! And guess what? You can use a regular expression to check if a string follows the syntax of an IPv4 address. How cool is that? (Source)

5. IPv6 Address

Or, you could check for the newer IPv6 syntax by using this more advanced regex snippet. It’s a small but important difference to keep in mind during development. (Source)

Now, let’s move on to number 6 – the “Thousands Separator.” In traditional numbering systems, we often use commas or periods as marks to separate every third digit in larger numbers. This regex code can be applied to any number and will add whatever mark you choose to every third digit, making it easier to read and understand. So if you’re dealing with thousands, millions, or even larger numbers, this can come in handy. (Source)

Next up is number 7 – the “Prepend HTTP to Hyperlink.” This regular expression is useful in JavaScript, Ruby, or PHP. It checks any URL string to see if it has an HTTP or HTTPS prefix. If it doesn’t, it will automatically add the prefix for you. This can save you time and hassle when dealing with URLs in your code. (Source)

Lastly, let’s take a look at number 8 – “Pull Domain from URL.” This regex code allows you to extract the domain from a URL. Whether you’re working with URLs in JavaScript, Ruby, or PHP, this regular expression can be a handy tool to have in your arsenal. It simplifies the process of extracting the domain from a URL, making it easier to work with and manipulate. (Source)

Every website address has a fancy protocol (HTTP or HTTPS), some added bits called subdomains, and often a long path to a specific page. But you don’t need all that extra stuff! This nifty code snippet can help you cut through the clutter and get just the simple domain name.

You know, sometimes it’s helpful to have a list of keywords sorted by the number of words in them. If you use Google Analytics or Webmaster Tools, you’re in luck! This regular expression can help you organize your keywords based on how many words are in each search term. It’s a real time-saver!

This is a powerful expression that can be used to sort analytics data, whether you want to specify a specific number of words or a range. (Source)

10. Discover a Valid Base64 String in PHP

\?php[\t]eval\(base64_decode\(‘(([A-Za-z0-9+/])*([A-Za-z0-9+/]= [A-Za-z0-9+/]==)?)’\)\);

If you’re a PHP developer, there may come a time when you need to search for Base64 encoded binary objects in your code. You can use this small code snippet in any PHP code to check for existing Base64 strings. (Source)

11. Validate Phone Numbers

^\+?\d?[- .]?\(?(?:\d)\)?[- .]?\d{3}[- .]?\d{4}$

This regex code is short and straightforward. It can validate phone numbers based on the traditional American format.

When it comes to whitespace in a string, things can get a bit tricky. If you need a deeper understanding, you can check out this Stack thread for more detailed answers. (Source)

12. What to do with Leading & Trailing Whitespace

Want to trim leading and trailing whitespace from a string? No worries, here’s a handy code snippet you can use. It may not seem like a big deal, but sometimes those pesky extra spaces can mess up your output, especially when you’re working with databases or applying the string to another document encoding. (Source)

13. How to Pull an Image Source

\< *[img][^\>]*[src] *= *[\”\’]([^\”\’\ >]*)

Need to extract an image’s source straight from the HTML? Look no further! This handy code snippet is the perfect solution. Although it works well on the backend, frontend JavaScript developers should consider using jQuery’s .attr() method instead. (Source)

14. How to Validate a Date in DD/MM/YYYY Format

Dates can be tricky because they come in different formats – they can be a combination of text and numbers, or just numbers. While PHP has a great date function, it may not always be the best option when dealing with raw strings. Instead, you can use this regular expression specifically designed for this type of date format. (Source)

Here’s a regular expression that can match YouTube video IDs. It’s perfect for extracting the video ID from various YouTube URL structures. YouTube has maintained the same URL structure for a long time because it simply works. Since YouTube is the most popular video sharing site on the web, videos from it tend to drive a lot of traffic. (Source)

If you’re looking to validate an ISBN (International Standard Book Number), you can use this regular expression. It can handle different variants of the ISBN format and ensure its validity. (Source)

Hey there! Did you know that with this awesome PHP code snippet, you can easily validate an ISBN number and determine if it’s an ISBN10 or an ISBN13? It’s super handy for web developers like you and me. (Source)

17. Let’s Check Out Zip Codes

This nifty code snippet is not just given away for free – the creator even took the time to explain it! Whether you’re dealing with a regular 5-digit zip code or a longer 9-digit one, this snippet will come in handy.

Just keep in mind, it’s primarily designed for the American zip code system. So if you’re using it for other countries, you might need to make some adjustments. (Source)

18. Confirm your Twitter Username

/@([A-Za-z0-9_])/

19. Credit Card Numbers

^(?:4[0-9](?:[0-9])? 5[1-5][0-9] 6(?:011 5[0-9][0-9])[0-9] 3[47][0-9] 3(?:0[0-5] [68][0-9])[0-9] (?:2131 1800 35\d)\d)$

When it comes to checking if a credit card number is valid, I’d usually turn to a secure platform online. But who knew, regex can do its thing and handle the basic requirements of a regular credit card number.

If you’re interested, there’s a whole bunch of codes for different types of cards you can dig into. You’ll find everything from Visa and MasterCard to Discover and more. (Source)

20. Find CSS Attributes

^\s*[a-zA-Z\-]+\s*[:]\s[a-zA-Z0-9\s.#]+[;]

It’s not everyday that you see someone using regex with CSS, but hey, it’s not that strange either.

Hey there! I have a really cool code snippet to share with you. It can do some pretty neat things, like extracting specific CSS properties and values from selectors. You can use it for a bunch of different reasons, like checking out chunks of CSS or getting rid of duplicate properties. How awesome is that? (Source)

21. Bye Bye HTML Comments

Ever need to get rid of all those pesky comments in a block of HTML? Well, I’ve got just the thing for you! Check out this super handy regex code. It’ll do the trick. And just to show you how it works, I’ve included a PHP example using preg_replace. Pretty nifty, huh? (Source)

22. Facebook Profile URL

/(?:http:\/\/)?(?:www\.)?facebook\.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-]*)/

Hey there! You know, Facebook is super popular. It’s been around for a while and has gone through a bunch of changes. Sometimes, when you’re dealing with user profile URLs, it’s handy to check if they’re structured correctly. Well, lucky for you, I’ve got a little code snippet that can do just that! This snippet works for any type of Facebook-style link you might come across. Pretty neat, huh? (Source)

23. Guess what? You can check the version of Internet Explorer!

^.*MSIE [5-8](?:\.[0-9]+)?(. *Trident\/[5-9]\.0).*$

So, you know how Microsoft came up with a cool new browser called Edge? Well, not everyone hopped on the Edge train. Some folks still rely on the classic Internet Explorer. And let me tell you, as a developer, it can be a real headache dealing with the inconsistencies between different versions of IE. That’s why it’s useful to be able to check which version of Internet Explorer (from 5 to 11) someone is using. Lucky for you, this little code snippet can help you out with that! You can use it in your JavaScript code to test the browser agent and figure out the version of IE being used. How cool is that? (Source)

24. Want to extract prices? No problem!

/(\$[0-9,]+(\.[0-9])?)/

Hey there! Let’s talk about pricing. It can get pretty tricky with decimal points, commas, and currency symbols. But don’t worry, I’ve got just the thing to help you out. This super cool code snippet uses something called a regular expression to check all these different formats and extract prices from any text. How awesome is that? (Source)

25. Find the Email Address

/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.[A-Z])\b/i

Guess what? With just one line of code, you can easily find the email address from an email header. It’s perfect if you need to extract the “to” information. And you know what’s even cooler? It works even if you have multiple emails joined together! How neat is that?

If you’re not a fan of regular expressions for this task, no worries! There are parsing libraries out there that can do the job just as well. (Source)

26. Match a Specific File Type

/^(.*\.(?!(htm|html|class|js)$))?[^.]*$/i

Let’s say you want to find a specific file type, like a document or a picture. This regular expression can help you do just that. It’s like a filter that lets you match files with any extension, except for htm, html, class, and js. How cool is that? Give it a try!

Dealing with different file formats like .xml, .html, and .js can be confusing. It’s helpful to check if files are valid, whether they are local or uploaded by users. The code snippet below can be used to pull the file extension and verify if it matches with the list of valid extensions:

let validExtensions = [‘.xml’, ‘.html’, ‘.js’];

let fileExtension = getFileExtension(filePath);

if (validExtensions.includes(fileExtension)) {

// File is valid

} else {

// File is invalid

}

This code can be customized by changing the validExtensions array to include different extensions as needed.

27. Check if a URL String is Valid

This code snippet can be used to check if a given URL string is valid, whether it starts with “http://” or “https://”. It matches the traditional TLD (Top-Level Domain) syntax:

let urlString = “https://www.example.com”;

let urlRegex = /[-a-zA-Z0-9@:%_\+.~#?&//=]\.[a-z]\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;

if (urlRegex.test(urlString)) {

// URL is valid

} else {

// URL is invalid

}

You can use this regex pattern to validate both HTTPS and HTTP strings.

28. Add rel=”nofollow” to Links

This code snippet can be used to append the rel=”nofollow” attribute to HTML anchor links. It prevents search engines from crawling and indexing the linked page:

let links = document.querySelectorAll(“a”);

links.forEach(function(link) {

let href = link.getAttribute(“href”);

if (href && !isInFollowList(href)) {

link.setAttribute(“rel”, “nofollow”);

}

});

You can customize the follow_list array to include specific domains that should not have the rel=”nofollow” attribute.

Hey there! I’ve got a cool code snippet to share with you. It’s about pulling anchor links from a block of HTML and adding the rel=”nofollow” attribute to them. I found this awesome code written by a helpful developer who even included a working example in PHP.

29. Media Query Match

/@media([^)\s*>/g

Do you want to break down CSS media queries and analyze their parameters and properties more easily? This code can help you out! It allows you to focus directly on understanding how the CSS operates. (Source)

30. Google Search Syntax

Guess what? You can create your own regex code to manipulate searchable text using Google’s special syntax. Use the plus sign (+) for additional keywords and the minus sign (-) to remove unwanted words from the results. How cool is that?

I know it might seem a bit complicated, but if you use this code correctly, it can be the foundation for creating your own search algorithm. (Source)

Conclusion

The journey to becoming a regex expert may take some time, but it’s definitely worth it. In addition to using regular expression tools, the best way to learn is through practice. Try developing web applications that utilize these regex snippets, and see how they function in a real web app. And if you have any other snippets to recommend, feel free to share them in the comments section below.

The journey to becoming a regex expert may take some time, but it’s definitely worth it. In addition to using regular expression tools, the best way to learn is through practice. Try developing web applications that utilize these regex snippets, and see how they function in a real web app. And if you have any other snippets to recommend, feel free to share them in the comments section below.