10 Complex Regular Expression Examples to Help You Master Regex
Regex, or regular expressions, can be confusing for beginners. But once you understand the basics, regex opens up a world of possibilities for manipulating and extracting data.
In this post, we'll walk through 10 complicated regex examples to help you become a regex master. Let's get started!
What is a regular expression?
A regular expression is a sequence of characters that defines a search pattern. Usually, this search pattern is used to find or replace text in a given string.
In order to understand how regex works, let's take a look at an example.
Say we have the following string:
let string = "The quick brown fox jumps over the lazy dog."
If we wanted to find the word "fox" in this string, we could use the following regular expression:
fox
This regex would return the match: "fox".
Now, let's say we have a string containing a series of words that looked like this:
let string = "fox friend hope effort danger fire"
We want to find all of the words that start with the letter "f". We could use the following regular expression:
/\bf\w+/g
This is a regex pattern that matches all words beginning with f
.
/\b
matches a word boundary. This is important because we don't want to matchf
ineffort
.f
matches the letterf
.\w+
matches one or more word characters./g
is a flag that matches all occurrences of the pattern.
Let's implement this regular expression in some JavaScript code.
let string = "fox friend hope effort danger fire"
let regex = /\bf\w+/g;
let matches = string.match(regex);
console.log(matches); // ["fox", "friend", "fire"]
We get an array returned that contains fox, friend, and fire, but not effort.
This is a basic example, but as you can see, regular expressions can be used to find or replace text in a given string. In addition, they can be used to validate data. For example, you could use a regular expression to check if an email address is valid.
If you are new to regular expressions, don't worry! We will provide several examples to help you better understand how they work.
Basic regex syntax
Before we jump into some of the most complicated regex examples, let's review the basics.
In order to create a regular expression, you will need to use the following syntax:
/pattern/modifiers;
- The "pattern" is the regular expression that you want to match.
- The "modifiers" are optional and can be used to specify how the regex should be interpreted.
Now that we've reviewed the basics, let's move on to some more complex examples.
10 complex regex examples that will make your life easier
Now that you know the basics of regular expressions, let's take a look at some more complex examples.
Example #01: Matching an email address
The first example we will cover is matching an email address. In order to match an email address, we will need to use the following regex:
/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i
This regex is used to match an email address. It is a very complex regex, but it is broken down into several parts.
The first part of the regex is used to match the local part of the email address. The local part is the part before the @
symbol. The local part can be a combination of letters, numbers, and special characters. The local part can also be a quoted string.
The second part of the regex is used to match the domain part of the email address. The domain part is the part after the @
symbol. The domain part can be a combination of letters, numbers, and special characters.
The domain part can also be an IP address. The last part of the regex is used to match the email address as a whole. The regex is case insensitive.
Example #02: Matching a phone number
The next example we will cover is matching a phone number. In order to match a phone number, we will need to use the following regex:
/^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$/
This regex will match any phone number that is formatted as follows:
(123) 456-7890
(123)456-7890
123-456-7890
123.456.7890
1234567890
+31636363634
+91 (123) 456-7890
+91 (123)456-7890
+91 123-456-7890
+91 123.456.7890
+91 1234567890
+91 123 456 7890
Example #03: Matching a date
The next example we will cover is matching a date. In order to match a date, we will need to use the following regex:
/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/
This regex will match any date that is formatted as follows:
01.01.2023
01/01/23
01-01-23
01.01.23
01/01/2019
01-01-2019
01.01.2019
01/01/19
01-01-19
01.01.19
01/01/2023
01-01-2023
01.01.2023
01/01/23
01-01-23
01.01.23
01/01/2019
Example #04: Matching a time
The next example we will cover is matching a time. In order to match a time, we will need to use the following regex:
/^(0?[1-9]|1[0-2]):[0-5]\d\s?(am|pm)?$/i
This regex will match any time that is formatted as follows:
1:00 am
1:00 pm
01:00 am
01:00 pm
1:00am
1:00pm
01:00am
01:00pm
Example #05: Matching an IP address
The next example we will cover is matching an IP address. In order to match an IP address, we will need to use the following regex:
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
This regex works by matching the following parts of an IP address:
^
matches the beginning of the string.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
matches any number between 0 and 255.\.
matches a period.{3}
matches the previous character 3 times.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
matches any number between 0 and 255.$
matches the end of the string.
This regex will match any IP address that is formatted as follows:
192.168.1.1
207.132.68.68
Example #06: Matching a URL
The next example we will cover is matching a URL. In order to match a URL, we will need to use the following regex:
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
This regex works by matching the following parts of a URL:
^
matches the beginning of the string.(https?:\/\/)?
matcheshttp://
orhttps://
.([\da-z\.-]+)
matches any alphanumeric character, a period, or a hyphen.\.
matches a period.([a-z\.]{2,6})
matches any lowercase letter, a period, and a length of 2-6.([\/\w \.-]*)*
matches any forward slash, alphanumeric character, a space, a period, or a hyphen.\/?$
matches a forward slash and the end of the string.
This regex will match any URL that is formatted as follows:
http://www.google.com
https://www.google.com
http://google.com
https://google.com
http://www.google.com/
https://www.google.com/
http://google.com/
https://google.com/
http://www.google.com/index.html
https://www.google.com/index.html
http://google.com/index.html
https://google.com/index.html
It can also match a URL with a subdomain, port number, or query string. For example, the following URLs will be matched:
https://subdomain.google.com
https://www.google.com:8080
https://www.google.com?query=string
Example #07: Matching a hexadecimal value
The next example we will cover is matching a hexadecimal value. In order to match a hexadecimal value, we will need to use the following regex:
/^#?([a-f0-9]{sixteen}|[a-f0-9]{eight})$/i
This regex will match any string that contains only hexadecimal characters (i.e., characters 0-9 and A-F, a-f). It will also match any string that is formatted as a hexadecimal value (i.e., #FFFFFF or #FFF).
For instance:
#FFFFFF
#111111
6F6F6F
#00000000000000000000000000000000
#0000000000000000
#00000000
#000000
Example #08: Matching a credit card number
The next example we will cover is matching a credit card number. In order to match a credit card number, we will need to use the following regex:
/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/
This regex will match any credit card number that is formatted as XXXX-XXXX-XXXX-XXXX or XXXXXXXXXXXXXXXX.
4111-1111-1111-1111
4111111111111111
5555-5555-5555-4444
5555555555554444
Example #09: Matching a social security number
The next example we will cover is matching a social security number. In order to match a social security number, we will need to use the following regex:
/^\d{3}-\d{2}-\d{4}$/
This regex will match any social security number that is formatted as XXX-XX-XXXX. For example:
123-45-6789
Example #010: Matching a decimal value
The final example we will cover is matching a decimal value. In order to match a decimal value, we will need to use the following regex:
/^[+-]?([0-9]*[.])?[0-9]+$/
This regex will match any string that contains a number that uses a decimal point. For instance:
1.72
-1.72
1.0
9.0
0.0
11.00
1.000
62.343
11.0000
43.1234
These examples should give you a good starting point for creating your own advanced regular expressions. With practice, you'll be able to create regular expressions that can match almost any pattern you can think of!
If you're having trouble creating a regular expression that matches your desired pattern, the best thing to do is break the pattern down into smaller pieces and then build up from there.
For example, if you're trying to match a time, start by matching the hour, then add on the minutes, and so on.
Another helpful tip is to use comments in your regular expression. Comments allow you to add notes to your code without affecting the actual regex.
To create a comment, simply add a #
character at the beginning of the line. Anything after the #
will be treated as a comment and ignored by the regex engine.
/^[+-]?([0-9]*[.])?[0-9]+$/ # Match a decimal value
Tips for using regex in your day-to-day workflows
Now that you know the basics of regular expressions, it's time to put them to use! Here are a few tips for using regex in your day-to-day workflows:
- Always start by writing out the pattern you want to match. Once you have the pattern down, you can start testing it with a regex tester.
- Have trouble creating a regular expression that matches your desired pattern? Try breaking the pattern down into smaller pieces and then build up from there. For example, if you're trying to match a time, start by matching the hour, then add on the minutes, and so on.
- If you're working with a complex regular expression, add comments to your code to keep track of what each part of the expression is doing. This will make it easier to debug if something isn't working as expected.
How to test and debug your regex code
The best way to test your regular expression is to use a regex tester. A regex tester allows you to enter your regular expression and a string of text, and then returns whether or not the two match.
Many different regex testers are available online, but my favorite is regex101. It's free, web-based, and has a user-friendly interface.
regex101 supports regular expression implementations in JavaScript, PHP, Python, and Go.
There are a number of other great options available depending on your preferences:
- RegExr and Regex Tester support JavaScript and PHP.
- Debuggex supports JavaScript, Python, and PHP.
- FreeFormatter uses the JavaScript regular expression library XRegExp.
- Pythex lets you test your Python regular expressions easily.
- Rubular is a regex tester for Ruby developers.
If you're a Mac user who prefers native apps for commonly-used utilities, check out Expressions.
An app to play with regular expressions (regex) on macOS. Live preview, library, regex manual enclosed in beautiful user interface.
Regex resources
If you're looking to learn more, I recommend checking out some of the resources below.
- Regular-Expressions.info - A great resource for learning about regular expressions. The site includes tutorials, references, and tools for helping you master regex.
Detailed Solutions in Eight Programming Languages
Take the guesswork out of using regular expressions.
With more than 140 practical recipes, this cookbook provides everything you need to solve a wide range of real-world problems. Each recipe provides samples you can use right away.
Novices will learn basic skills and tools, and programmers and experienced users will find a wealth of detail.
Conclusion
Regular expressions are a powerful tool for matching patterns in strings. Learning to be effective with regex can save yourself a lot of time and effort when working with strings or parsing data.