Delimiters
Regular expressions must start and end with the same exact character. The two most common are below (although almost any non-alphanumeric character can be used).
CharactersCode:/pattern/ #pattern#
The most basic regular expression contains a single literal character. However using literals greatly restricts the capabilities of regular expressions. For that reason several special characters have been defined.
Character ClassesCode:. (dot) match any single character \d match a digit 0-9 \w match an alphanumeric character \s match a white space \D match a non digit \W match a non aplhanumeric character \S match a non space
Character classes are used to match one out of several characters. To use a character class, simply surround your characters by square brackets: [ and ]. You should note that unless otherwise specified, regular expressions are case sensitive (more on this later). Moreover a hyphen can be used to specify a range of characters.
QuantifiersCode:[abc123] match a, b, c, 1, 2 or 3 [a-c1-3] match a, b, c, 1, 2 or 3 [a-z] match a lower case letters [0-9] same as \d [a-zA-Z] match a lowercase or uppercase letter
Often times you want to match a character or character class a certain amount of times. Quantifiers precede characters and character classes.
ExamplesCode:? match an item zero or one times * match an item zero or more times + match an item one or more times {n} match an item n times {n,m} match an item between n and m times {n,} match an item n or more times
Below are several examples. As with any programming problem, there are always more than one way to do something. Each expression is placed on its own line and matches the pattern above.
Pattern: 1234
Pattern: A domain name ending in .comCode:/1234/ This only matches the pattern 1234 /\d\d\d\d/ This matches any four digits /\d{4}/ This matches any four digits /[1-4]{4}/ This matches four digits that are between 1 and 4 inclusive
To see more examples, have a look at my validation class.Code:/[a-zA-Z0-9-]+.com/
Great thanks a lot! This will be very helpful, and be a great reference for me.
ThanksBookmarked this, and will come back often for a reference.
Thanks![]()
I will also come back to this often for a reference. It's a lot easier than digging through my books lol
Nice reference resource. I will use this often.
Posted via CodeCall Mobile
Nice reference, this will definitely help me instead of google searches lol. +rep / +bookmark!
John's posts on here have a way of appearing on Google in the top 10 anyway. We will probably see it there soon.
I believe we should turn this into a Cheat Sheet. I don't know about the rest of you, but I wouldn't mind having this hung up on the wall in my office for reference. What does everyone else think?
I've seen some RegEx cheatsheets before. I love cheatsheets![]()
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks