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).
/pattern/ #pattern#
Characters
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.
. (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
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.
[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
Quantifiers
Often times you want to match a character or character class a certain amount of times. Quantifiers precede characters and character classes.
? 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 [I]n[/I] times
{n,m} match an item between [I]n[/I] and [I]m[/I] times
{n,} match an item [I]n[/I] or more times Examples
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
/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
Pattern: A domain name ending in .com
/[a-zA-Z0-9-]+.com/
To see more examples, have a look at my validation class.


Sign In
Create Account

Back to top










