Text Processing
Regex Match
A regular expression can match text and capture useful parts.
regex capture
Parentheses in a regular expression capture part of a match for later use.
Regex Match
regex_match.rb
Replay: real traced execution (multi-file project)
email = "ada@example.com"
match = email.match(/\A([^@]+)@([^@]+)\z/)
if match
puts "user=#{match[1]}"
puts "domain=#{match[2]}"
else
puts "email=invalid"
end
email = "bad-email"
match = email.match(/\A([^@]+)@([^@]+)\z/)
if match
puts "user=#{match[1]}"
puts "domain=#{match[2]}"
else
puts "email=invalid"
end
email = "matz@ruby.org"
match = email.match(/\A([^@]+)@([^@]+)\z/)
if match
puts "user=#{match[1]}"
puts "domain=#{match[2]}"
else
puts "email=invalid"
end
email ← ada@example.com, match ← ada@example.com
1email→ ada@example.com = "ada@example.com" #@email="bad-email", "matz@ruby.org"23match→ ada@example.com = email.match(/\A([^@]+)@([^@]+)\z/)ada@example.comif match
5if matchada@example.com6 puts "user=#{match[1]ada}"7 puts "domain=#{match[2]example.com}"8elseoutputuser=ada domain=example.com
email ← bad-email, match ← (empty)
1email→ bad-email = "bad-email"23match→ (empty) = email.match(/\A([^@]+)@([^@]+)\z/)(empty)else
7 puts "domain=#{match[2]}"8else9 puts "email=invalid"10endoutputemail=invalid
email ← matz@ruby.org, match ← matz@ruby.org
1email→ matz@ruby.org = "matz@ruby.org"23match→ matz@ruby.org = email.match(/\A([^@]+)@([^@]+)\z/)matz@ruby.orgif match
5if matchmatz@ruby.org6 puts "user=#{match[1]matz}"7 puts "domain=#{match[2]ruby.org}"8elseoutputuser=matz domain=ruby.org