๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Regular Expressions

A regular expression is a pattern written between two slashes. It finds text that fits the pattern inside a string.

Reading a capture group

The match call fits the pattern against the text. The digits sit inside round brackets, so they form a capture group.

text = "order 42 ships today"
m = text.match(/order (\d+)/)
puts m[0]
puts m[1]

Finding a position with =~

The =~ operator gives the position where the match starts. It gives nil when the pattern fits nowhere.

puts "hello world" =~ /world/
result = "hello" =~ /z/
puts result.nil?

Collecting matches with scan

scan walks the whole string and keeps every match. The matches come back as an array of strings.

text = "a1 b2 c3"
p text.scan(/\d/)

Replacing with a pattern

gsub also accepts a pattern between slashes. Here every run of digits becomes one dash.

text = "cat123dog45"
puts text.gsub(/\d+/, "-")

Example

label = "room 204 on floor 3"
m = label.match(/room (\d+)/)
puts m[1]
p label.scan(/\d+/)

Key points

  • match returns a MatchData object for the first match it finds.
  • Text in round brackets forms a capture group.
  • m[1] reads the first capture group from a MatchData.
  • scan collects every match in an array.
  • The =~ operator returns the position of the first match.
  • =~ returns nil when nothing matches.

In this example, match fits the pattern room followed by digits. The capture group holds 204, and m[1] reads it. The scan call then collects every run of digits in the string as an array.

Note

A pattern like \d stands for one digit character.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does "abc123".match(/(\d+)/)[1] give?