Regex, or Regular Expression, is a powerful tool used for pattern matching in strings. In this section, we will delve deeper into the concept of regex and explore some advanced patterns.
Advanced Regex Patterns
Lookahead and Lookbehind Assertions These assertions allow you to specify conditions that must be true for a match to occur, without including the matched text in the result.
a(?=b) # Matches 'a' only if it is followed by 'b' a(?!b) # Matches 'a' only if it is not followed by 'b'
Named Groups Named groups provide a way to reference a group of characters by name, which can be useful for extracting specific parts of a string.
(?<name>pattern)
Quantifiers with Specific Ranges You can specify a range for quantifiers to match a certain number of occurrences.
a{1,3} # Matches 'a' between 1 and 3 times
Character Classes with Negation Character classes can be used to match a set of characters, and you can also use negation to exclude certain characters.
[a-z] # Matches any lowercase letter [^a-z] # Matches any character that is not a lowercase letter
Useful Regex Patterns
Here are some commonly used regex patterns:
- Email Address: `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$
- Phone Number:
\+?(\d{1,3})?[-. ]?(\(\d{3}\)|\d{3})[-. ]?\d{3}[-. ]?\d{4}
- URL:
(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?
Learn More
If you are interested in learning more about regex, we recommend checking out our Regex Tutorial. It covers the basics and advanced concepts in detail.