Regular Expressions in Crystal

Our program demonstrates common regular expression operations in Crystal. Here’s the full source code:

require "regex"

# This tests whether a pattern matches a string.
match = /p([a-z]+)ch/.match("peach")
puts match

# For other regex tasks, you'll use the Regex class.
r = /p([a-z]+)ch/

# Here's a match test like we saw earlier.
puts r.match("peach")

# This finds the match for the regex.
puts r.match("peach punch").try(&.[0])

# This also finds the first match but returns the
# start and end indexes for the match instead of the
# matching text.
puts "idx: #{r.match("peach punch").try(&.begin)}..#{r.match("peach punch").try(&.end)}"

# The named_captures method includes information about
# both the whole-pattern matches and the captures
# within those matches.
puts r.match("peach punch").try(&.named_captures)

# To find all matches for a regex:
puts "peach punch pinch".scan(r).map(&.[0])

# Providing a limit as the second argument will limit the number
# of matches.
puts "peach punch pinch".scan(r, 2).map(&.[0])

# The regex package can also be used to replace
# subsets of strings with other values.
puts "a peach".gsub(r, "<fruit>")

# The with_index method allows you to transform matched
# text with a given block.
in_bytes = "a peach".bytes
out_bytes = in_bytes.map_with_index do |byte, index|
  if r.match(in_bytes[index..].map(&.chr).join)
    byte.chr.upcase.bytes[0]
  else
    byte
  end
end
puts String.new(out_bytes)

To run the program, save it as regular_expressions.cr and use the crystal command:

$ crystal regular_expressions.cr
#<Regex::MatchData "peach" ea>
#<Regex::MatchData "peach" ea>
peach
idx: 0..5
{"0" => "peach", "1" => "ea"}
["peach", "punch", "pinch"]
["peach", "punch"]
a <fruit>
a PEACH

Crystal’s regular expression support is similar to Ruby’s, which it is heavily inspired by. The Regex class provides most of the functionality, and there are convenient methods on String for common operations.

For a complete reference on Crystal regular expressions, check the official Crystal documentation.