July 2007
Intermediate to advanced
128 pages
2h 39m
English
Example 1-21. Simple match
#Find Spider-Man, Spiderman, SPIDER-MAN, etc.
dailybugle = 'Spider-Man Menaces City!'
if dailybugle.match(/spider[- ]?man./i)
puts dailybugle
endExample 1-22. Match and capture group
#Match dates formatted like MM/DD/YYYY, MM-DD-YY,...
date = '12/30/1969'
regexp = Regexp.new('^(\d\d)[-/](\d\d)[-/](\d\d(?:\d\d)?)$')
if md = regexp.match(date)
month = md[1] #12
day = md[2] #30
year = md[3] #1969
end
Example 1-23. Simple substitution
#Convert <br> to <br /> for XHTML compliance
text = 'Hello world. <br>'
regexp = Regexp.new('<br>', Regexp::IGNORECASE)
result = text.sub(regexp, "<br />")Example 1-24. Harder substitution
#urlify - turn URLs into HTML links
text = 'Check the web site, http://www.oreilly.com/catalog/regexppr.'
regexp = Regexp.new('
\b # start at word boundary
( # capture to \1
(https?|telnet|gopher|file|wais|ftp) :
# resource and colon
[\w/#~:.?+=&%@!\-] +? # one or more valid chars
# take little as possible
)
(?= # lookahead
[.:?\-] * # for possible punc
(?: [^\w/#~:.?+=&%@!\-] # invalid character
| $ ) # or end of string
)', Regexp::EXTENDED)
result = text.sub(regexp, '<a href="\1">\1</a>')