← Back to Ruby Operators

Regex Literal

Two forward slashes (/) wrapped around a pattern gives us a regex (regular expression) literal in Ruby. We can use these to check that a string conforms to a specified shape or to extract values from predictably shaped input, among other things.

In the simplest case, we can use a regex literal to check for a partial match against a string.

> pattern = /bar/
=> /bar/
> pattern =~ "barrel"
=> 0
> pattern =~ "disbarment"
=> 3
> pattern =~ "Cocktail Bar"
=> nil

Or we can introduce some Boundary Anchors and metacharacters to do a very rough email validation.

> email_regex = /\A.*@.*\z/
=> /\A.*@.*\z/
> email_regex.match('[email protected]')
=> #<MatchData "[email protected]">
> email_regex.match('Bob Burgers')
=> nil

Here as a real-world example of a regex literal from the Rails codebase for validating the format of a migration filename.

MigrationFilenameRegexp = /\A([0-9]+)_([_a-z0-9]*).?([_a-z0-9]*)?.rb\z/

The different metacharacters, character classes, functionality like capture groups, and so forth are out of the scope of what is covered on this page. Check out more under the Sources section of the Regexp Ruby Docs.

References