Regular Expresions: "Regex"
Student Learning Objectives:
Why learn Regular Expressions:
-
Regular Expressions are a part of many programming languages: Ruby, JS, Perl, Python, Java, unix shell scripts (grep) ...
-
Regular Expressions are used for pattern matching, find and replace tasks.
-
Good for model validations: valid email format, valid phone format, valid ssn ...
-
Regex is real cryptic code. You have to decipher it to understand it.
1) Match a pattern in a string
-
The strategy is to only match what you want.
-
Each character in a regex is either a metacharacter with special meaning, or a regular character with its literal meaning.
-
*
Place exact string between to forward slashes: /cat/ matches "cat"
* However, /cat/ also matches "catastrophe" and "scat"
-
Use metacharacters to be more specific on what you match.
-
-
Dogs are not dogmatic about dog things unlike Madog the bad dog.
-
. - wild card, matches any char
-
\ - escape a character, turns a metacharacter into a string literal - to match a literal period use \\.
-
| - logical or, /cat|dog/ matches "cat" or "dog"
-
\s - matches any whitespace
-
\S - matches any non-whitespace
-
-
-
/cAt/i - "/i" case insensitive, matches Cat, cAt, CAT, CaT, cat ...
-
open "match_string.rb" in sublime, and follow the instructions within
-
run using: $ruby match_string.rb string_data
2) Select section out of a string
-
(...) - enclosed matches are assigned variable names $1+ that can be reused
-
[] - range of characters or numbers to match: [0-9] or [a-z]
-
\d - any digit, same as [0-9]
-
-
{} - exact number of times character or number is repeated, a{2} == "aa"
-
-
-
-
open "real_time_data.rb" in sublime, and follow the instructions within
-
run using: $ruby read_time_data.rb time_data
3) Find and replace parts of a string
-
-
.sub substitutes on first match, .gsub substitutes globally all matches
-
Syntax: my_string.sub( /sub string to match/ , "replacement sub string" )
-
"That is a cute dog.".sub(/dog/, "cat") => "That is a cute cat."
-
*
"Red is my favorite color, I just love red".sub(/red/, "blue").sub(/Red/,"Blue")
-
open "find_replace.rb" in sublime, and follow the instructions within
-
run using: $ruby find_replace.rb find_replace_data
##@@@@@@@@@@@@@@@@@@@@@@@@