Top 15 Commonly Used Regex
Regular Expressions aka Regex are expressions that define a search pattern. They are widely used for validation purposes, like email validation, url validation, phone number validation and so on.
When I was starting out with regular expressions I got recommended this book: Mastering Regular Expressions. It really helped me understand the basic concept and how regular expressions work. But also I can still learn from it today because it also covers more advanced topics. PHP has many useful functions to work with regular expressions. Here is a quick cheat sheet of the main PHP regex functions. Remember that all of them are case sensitive. For more information about the native functions for PHP regular expressions, have a look.
Forming Regex:
A regex is written between two forward slashes (/
) delimiters. These delimiters are essential only for certain Regex engines (JS,PHP.). How do i change the author name on word for mac 2011. It is then followed by 2 flags:
i
: Ignore case Flag, ignores the case(uppercase/lowercase) of the input stringg
: Global Flag, searches for multiple matches instead of stopping at the first match
A quick cheat sheet for those of you who do not remember all the rules of Regex Nudi software free for windows 8.
Cheat Sheet – Regex Rules
Character classes | Quantifiers & Alternation | ||
---|---|---|---|
. | any character except newline | a* a+ a? | 0 or more, 1 or more, 0 or 1 |
w d s | word, digit, whitespace | a{5} a{2,} | exactly five, two or more |
W D S | not word, digit, whitespace | a{1,3} | between one & three |
[abc] | any of a, b, or c | a+? a{2,}? | match as few as possible |
[^abc] | not a, b, or c | ab|cd | match ab or cd |
[a-g] | character between a & g | ||
Anchors | Groups & Lookaround | ||
^abc$ | start / end of the string | (abc) | capture group |
b | word boundary | 1 | backreference to group #1 |
Escaped characters | (?:abc) | non-capturing group | |
. * | is used to escape special chars. * matches * | (?=abc) | positive lookahead |
t n r | tab, linefeed, carriage return | (?!abc) | negative lookahead |
Commonly used Regex
1. Digits
- Whole Numbers –
/^d+$/
- Decimal Numbers –
/^d*.d+$/
- Whole + Decimal Numbers –
/^d*(.d+)?$/
- Negative, Positive Whole + Decimal Numbers –
/^-?d*(.d+)?$/
- Whole + Decimal + Fractions –
/[-]?[0-9]+[,.]?[0-9]*([/][0-9]+[,.]?[0-9]*)*/
2. Alphanumeric Characters
- Alphanumeric without space –
/^[a-zA-Z0-9]*$/
- Alphanumeric with space –
/^[a-zA-Z0-9 ]*$/
3. Email
- Common email Ids –
/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6})*$/
- Uncommon email ids –
/^([a-z0-9_.+-]+)@([da-z.-]+).([a-z.]{2,6})$/
4. Password Strength
- Complex: Should have 1 lowercase letter, 1 uppercase letter, 1 number, 1 special character and be at least 8 characters long
- Moderate: Should have 1 lowercase letter, 1 uppercase letter, 1 number, and be at least 8 characters long
5. Username
- Alphanumeric string that may include _ and – having a length of 3 to 16 characters –
/^[a-z0-9_-]{3,16}$/
6. URL
- Include http(s) Protocol
7. IP Address
- Both IPv4, IPv6 addresses
8. Dates
- Date Format YYYY-MM-dd using separator
-
- Date Format dd-MM-YYYY using separators
-
or.
or/
- Date Format dd-mmm-YYYY using separators
-
or.
or/
9. Time
- Time Format HH:MM 12-hour, optional leading 0
/^(0?[1-9]|1[0-2]):[0-5][0-9]$/
- Time Format HH:MM 12-hour, optional leading 0, Meridiems (AM/PM)
/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
- Time Format HH:MM 24-hour with leading 0
/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
- Time Format HH:MM 24-hour, optional leading 0
/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
- Time Format HH:MM:SS 24-hour
/(?:[01]d|2[0123]):(?:[012345]d):(?:[012345]d)/
10. HTML Tags
- Elements with Attributes
/</?[ws]*>|<.+[W]>/
11. Javascript Handlers
- Inline JS handler
/bonw+=S+(?=.*>)/
- Inline JS handler with element
/(?:<[^>]+s)(onS+)=[']?((?:.(?![']?s+(?:S+)=|[>']))+.)[']?/
12. Slug
- Slug
/^[a-z0-9]+(?:-[a-z0-9]+)*$/
13. Match Duplicates in a String
- Search Duplicates
/(bw+b)(?=.*b1b)/
14. Phone Numbers
- International Phone Numbers – with optional country code/extension
Note: Use regex for validating phone numbers only if you don’t have the choice to use a library. There are several libraries that handle phone numbers more accurately and should be used instead.
15. File Path
- File Path with optional Filename, extension
- File Name with extension having 3 chars
Additional Regexes
1. Zip codes
There is NO single Regex that can handle all zip codes given that zip codes around the world do not follow a common pattern. Here is a list that contains Regex specific to each country.
2. Payment Validation
Here is a link that contains regex for validating leading Credit cards like Visa, Mastercard and so on. Nch software keygen rar.
3. Identity Documents
- Social Security Number – Ref
- Passport –
/^[A-PR-WY][1-9]ds?d{4}[1-9]$/
References
P.s. Need a graphical explanation of any of the above Regex ? Try Regular Expression Visualization and copy-paste any Regex in the input box to get a graphical representation of it. Hope that helps!
Rex eats regular expressions for breakfast. And so can you! This regex tutorial, one of the most detailed on the web, takes you all the way to mastery.This page explains what makes this site special among all other regex sites, but first let's answer a burning question:
What is the meaning of life?
That's easy. As per the regex humor page, it's simply
^(?=(?!(.)1)([^DO:105-93+30])(?-1)(?<!d(?<=(?![5-90-3])d))).[^WHY?]$
Now for the other burning question…
What is a Regex?
First, a regex is a text string. For instance, foo is a regex. So is [A-Z]+:d+.Those text strings describe patterns to find text or positions within a body of text. For instance, the regex foo matches the string foo, the regex [A-Z]+:d+ matches string fragments like F:1 and GO:30, and the regex (?<=[a-z])(?=[A-Z]) matches the position in the string CamelCase where we shift from a lower-case letter to an upper-case letter.
Typically, these patterns (which can be beautifully intricate and precise) are used for four main tasks: to find text within a larger body of text; to validate that a string conforms to a desired format; to replace text (or
Php Regex Maker
insert text at matched positions, which is the same process); and to split strings.For instance, the CamelCase pattern from the last paragraph can be used to split MyLovelyValentine into its three component words. And you could use the regex _d+_ to find digits within underscores (as in _12_) and to replace the underscores with double dashes, yielding --12--, something you could not do with a conventional search-and-replace (details for that technique are in the recipe about replacing one delimiter with another).
Who does this work of finding, replacing, splitting? A regex engine. For instance, you can find regex engines in text editors such as Notepad++ and EditPad Pro. You also find regex engines ready to roar in most programming languages—such as C#, Python, Perl, PHP, Java, JavaScript and Ruby.
Php Cheat Sheet Pdf
Let's compress the definition from the earlier paragraphs:Is a Regex the same as a Regular Expression?
Mostly yes, with a little bit of no. At this stage, this is a semantic question—it depends on what one means by regular expression. That topic and other juicy details are discussed on the page about Regex vs. Regular Expressions.
About this Site
Before we dive in—and only if you have time—I'd like to introduce this site and what makes it special.I love regular expressions. They are a small computer language of their own.
When I was a young dinosaur, I didn't take the time to properly learn the syntax, largely because I really didn't feel like learning another language. Who needs regex, I thought, when your programming language has functions that let you dig into strings from the left, the middle and the right?
What's more, the raw syntax you usually see in code that contains regexes used to intimidate me. Who wants to deal with a language that looks like this?
(?s)/*(?:(?!*/)[*$ _/+-])*(.*?)[*$ _/+-]*?*/
No doubt about it, even with comments and breathing room, there is something raw and experimental about writing a regex pattern.
Besides, how well your pattern performs doesn't only depend on applying correct syntax. There are several ways of doing things, and various regex engines may optimize some of these ways behind your back.
With regex, you are stepping down to a fairly low level, within earshot of the machine room. I like that. And I've been liking it all the more since learning about tools and safeguards to keep me from falling into the boiler.
A (hopefully) Different Presentation of Regex
RexEgg tries to present regular expressions a bit differently, in the hope that these different angles help many people become more grounded in their knowledge of regex. If you are looking for a drawn-out primer, this is not the place, as I don't see the need to pollute our beautiful world wide web with another explanation of how to match 'foo' in 'foo bar'. But if you take your time to read the carefully-built tables on the quick-launch page then perhaps the page about (? … ) syntax, you will experience what may be the most accelerated regex introduction around.
What Will you Find on this Site
✽ A step-by-step explanation of simple and advanced regular expressions crafted for various contexts (such as text matching, file renaming, search-and-replace).
✽ A presentation of the many contexts where you may run into regular expressions (from Apache to your html editor and file manager), complete with examples.
✽ A reference about (? … )—to reduce confusion by bringing all the pieces of syntax that start with an opening parenthesis and a question mark into a single place.
✽ A discussion of Conditional Regexes, a topic about which there is little information.
✽ A discussion of Recursive Regexes, a topic about which there is very little information.
✽ Pages dedicated to regex in C#, Python, PHP and other languages.
✽ Plenty of tips & tricks.
✽ Sections about regex tools and regex books.
✽ And much more!
I wish you lots of fun on your journey with regular expressions.
Smiles,
Rex
and The Best Regex Trick Ever!!!
Quick-Start: Regex reference table