Tsallaka zuwa abun ciki
Justice Tech School

Regular Expressions

Regexes live between slashes. match, =~, scan, gsub and named captures extract and change text. $~ holds the last match.

Example
s = "Order 12 and 345, ref A-77"
puts s.scan(/\d+/).inspect
puts s =~ /and/
m = s.match(/(?<word>[A-Z])-(?<num>\d+)/)
puts m[:word], m[:num]
puts s.gsub(/\d+/) { |d| (d.to_i * 2).to_s }

Result

["12", "345", "77"]
9
A
77
Order 24 and 690, ref A-154

Exercise

Find all matches.

s.(/\d+/)

Quiz Test

What does scan return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.