Character Matchers
. (Any Character)
\d (Any Number)
\s (Any Whitespace)
\w (Any Word Character)
Slide 52
Slide 52 text
Quantifiers
* (Zero or more)
+ (One or more)
? (One or None)
{n,m} (Only n matches up to m)
Slide 53
Slide 53 text
Quantifiers
(part Deux)
Changes the number of matches to
the left of the quantifier.
a* (if there, match a, keep going)
a+ (must match a, keep going)
a? (if there, match a)
a{1,3} (matches a or aa or aaa)
Slide 54
Slide 54 text
Character Classes
[] (Matches groups of literal
characters)
[^] (Don’t match any of these
characters)
Slide 55
Slide 55 text
Character Classes
(gotcha)
[.+*] (Matches a dot, plus or
splat)
Any meta character inside a
character class becomes a literal
character
Slide 56
Slide 56 text
Character Classes
(part Deux)
\w = [A-Za-z0-9_]
\W = [^A-Za-z0-9_]
\s = [ \t\r\n]
The - is a range of literal
characters
Slide 57
Slide 57 text
Grouping
Combine matches into groups using
( and ) surrounding your matches.
(Hello) World
Matches Hello World and Hello
separately
Slide 58
Slide 58 text
Escaping
(from alcatraz)
Use \ to turn a metacharacter into
a literal
. Matches anything
\. Matches a period
Slide 59
Slide 59 text
/^Hello [Ww]orld.?$/
Slide 60
Slide 60 text
Break it Down!
Slide 61
Slide 61 text
/^Hello [Ww]orld.?$/
Slide 62
Slide 62 text
/^Hello [Ww]orld.?$/
Beginning
End
Exact letters H e l l o
(including space)
Exact letters o r l d
Anything
Maybe once?
Capital or lower-case W
Slide 63
Slide 63 text
/Hello World/
Hello World
Hi, Hello World
Say Hello World
Slide 64
Slide 64 text
/^Hello World$/
Hello World
Hi, Hello World
Say Hello World
Slide 65
Slide 65 text
/^Hello World.?$/
Hello World
Hello World!
Hello, World!
Hello, World
Slide 66
Slide 66 text
/^Hello [Ww]orld.?$/
Hello World!
Hello world
Hello World
Hello, world!
Slide 67
Slide 67 text
/^Hello [Ww]orld.?$/
Slide 68
Slide 68 text
/^Hello [Ww]orld.?$/
Beginning
End
Exact letters H e l l o
(including space)
Exact letters o r l d
Anything
Maybe once?
Capital or lower-case W
Slide 69
Slide 69 text
No content
Slide 70
Slide 70 text
Good Practices
Slide 71
Slide 71 text
Be Precise
Slide 72
Slide 72 text
No content
Slide 73
Slide 73 text
Don’t Be Greedy!
Slide 74
Slide 74 text
No content
Slide 75
Slide 75 text
Precision
Matches exactly what you want
Slide 76
Slide 76 text
Greed
Matches everything you don’t want
Slide 77
Slide 77 text
Precision vs Greed
Be as specific as you can!
Avoid use of the dot
.
Avoid greedy quantifiers
+ or .+
Options
Matching options (usually added after
the second /)
i - case insensitive
o - interpolate once (#{}’s)
m - multiline mode (‘.’ matches \n)
x - extended mode (ignore whitespace)
Slide 87
Slide 87 text
Options
(Extended Dvd Edition)
“Chunky Bacon”.match(/bacon/i).to_s
=> “Bacon”
Slide 88
Slide 88 text
1.9 Only
(but possible with Oniguruma gem)
Slide 89
Slide 89 text
POSIX Matchers
[:alpha:] = [a-zA-Z]
[:alnum:] = [a-zA-Z0-9]
Many, many more