Upload
nell-shamrell
View
156
Download
0
Embed Size (px)
Citation preview
Regular Expressions What are they and what can they do for you?
Thursday, February 7, 13
\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2-4}\b
Source: http://www.regular-expressions.info/email.html
Thursday, February 7, 13
So...what is a regular expression?
Thursday, February 7, 13
A Regular Expression is a pattern for a string.
Thursday, February 7, 13
What can you do with Regular Expressions?
Test a stringExtract a stringChange a string
Thursday, February 7, 13
Creating Regular Expressions
/RegularExpression/
Thursday, February 7, 13
Scenario #1Testing Strings
Thursday, February 7, 13
Examples from “Programming Ruby” (PickAxe)
Thursday, February 7, 13
“dog and cat”
Thursday, February 7, 13
“dog and cat”
/cat/
Thursday, February 7, 13
“dog and cat”
/cat/
/cat/ =~ “dog and cat”
Thursday, February 7, 13
=~/cat/ =~ “dog and cat”
Thursday, February 7, 13
Thursday, February 7, 13
Thursday, February 7, 13
match/cat/.match(“dog and cat”)
Thursday, February 7, 13
Valid Emails
Thursday, February 7, 13
Alternation/Nell | Brandon/
Thursday, February 7, 13
Metacharacters
any single character
character can appear any number of times
.*
Thursday, February 7, 13
.*//matches ANYTHING
Thursday, February 7, 13
Range[a-d] [1-4]
Thursday, February 7, 13
Shorthand!
\w stands for any word character.
It’s the same as:[a-zA-Z0-9_]
Thursday, February 7, 13
Metacharacters
character occurs one or more times+
Thursday, February 7, 13
Thursday, February 7, 13
Scenario #2Extracting Strings
Thursday, February 7, 13
Shorthand!
\d stands for any digit
\D stands for any non-digit
Thursday, February 7, 13
Repetition!
\d{3} Looks for exactly 3 digits
Thursday, February 7, 13
Make It Optional!
?Makes a character
optional. It can occur 0 or 1 time.
Thursday, February 7, 13
Scenario #3Changing Strings
Thursday, February 7, 13
“Brandon is the teacher of the class right now. Brandon is teaching about regular expressions.”
Thursday, February 7, 13
sub(/pattern/, “text”)
Thursday, February 7, 13
gsub(/pattern/, “text”)
(replace ALL the matches)
Thursday, February 7, 13
sub and gsub create new strings. sub! and gsub! change the original strings
Thursday, February 7, 13
Welcome to the wonderful world of Regular Expressions!
Thursday, February 7, 13