2 Types of RegEx: Matching & Substitution
Use an m (optional) for matching, and an s for substitution.
PERL RegEx
$string = "Perl is cool";
Matching
$string =~ m/cool/
Returns: True (1)
Substitution
$string =~ s/cool/chilly/;
Returns: Perl is chilly
Regular Expressions
Character Class Abbreviations
| . |
anything (except a \n) |
| \d |
a digit (0-9, same as [0-9]) |
| \w |
a word character (a-z, A-Z, 0-9, _, [a-zA-Z0-9_]) |
| \s |
a space character (space, tab, linefeed, carriage return, [ \t\n\f\r]) |
| \D |
not a digit (opposite of \d) |
| \W |
not a word character (opposite of \w) |
| \S |
not a space character (opposite of \s) |
|
Anchors
| ^ |
anchors to the beginning of the string |
| $ |
anchors to the end of the string |
| \b |
word boundary (between \w and \W or \w and beginning/end of a line) |
|
Multipliers
| {n} |
matches exactly n times |
| {n,} |
matches n or more times |
| {n,m} |
matches n to m times |
| * |
find 0 or more |
| + |
find 1 or more |
| ? |
find 0 or 1 |
|
Common Modifiers
| /i |
Ignore case |
| /g |
global -- match/substitute as often as possible |
|
Memory in RegEx
You can use parentheses to capture a matched piece of text for later use.
To recall the captured matched text:
- use \1, \2, \3 if still in RegEx
- use $1, $2, $3 if after the RegEx