Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

Regular Expressions

/regex will find me/

What are Regular Expressions


Regular expressions allow matching and

manipulation of textual data. Abbreviated as regex or regexp, or alternatively, just patterns

Regular Expressions in Ruby

Using Regular Expressions


Scan a string for multiple occurrences of a

pattern. Replace part of a string with another string. Split a string based on a matching separator.

Regular Expression Syntax


Regular expressions are put between two

forward slashes (/match_me/)


They are escaped with a backward slash (\).

Characters That Need to be Escaped


.|()[]{}+\^$*?

Regex Basics
[abc] A single character: a, b or c

[^abc] Any single character but a, b, or c


[a-z] Any single character in the range a-z [a-zA-Z] Any single character in the range a-z or

A-Z ^ Start of line $ End of line \A Start of string \z End of string

Regex Basics cont...


. Any single character

\s Any whitespace character


\S Any non-whitespace character \d Any digit \D Any non-digit \w Any word character (letter, number,

underscore) \W Any non-word character \b Any word boundary character

Regex Basics cont...


(...) Capture everything enclosed

(a|b) a or b
a? Zero or one of a a* Zero or more of a a+ One or more of a a{3} Exactly 3 of a a{3,} 3 or more of a a{3,6} Between 3 and 6 of a

Regex: .match
>> category = "power tools" => "power tools" >> puts "on Sale" if category.match(/power tools/) on Sale >> puts "on Sale" if /power tools/.match(category) on Sale

Regex: =~
>> category = "shoes" => "shoes" >> puts "15 % off" if category =~ /shoes/ 15 % off >> puts "15 % off" if /shoes/ =~ category 15 % off >> /pants/ =~ category => nil >> /shoes/ =~ category => 0 >> category = "women's shoes >> /shoes/ =~ category => 8

8th character

Scan
>> numbers = "one two three" => "one two three" >> numbers.scan(/\w+/) => ["one", "two", "three]

Split with Regular Expressions


>> "one two\tthree".split(/\s/) => ["one", two", "three"]

gsub
fred,mary,john".gsub(/fred/, XXX) => XXX,mary,john

gsub with a block


"one two\tthree".gsub(/(\w+)/) do |w| puts w end one two three

Title Case
Capitalize All Words of a Sentence: >> full_name.gsub(/\b\w/){|s| s.upcase} => "Yukihiro Matsumoto"

You might also like