Regular Expressions

Flashcard 6 of 10

How can we write a pattern that will find all instances of class or klass, but not class_name in the following passage?

The word class is a reserved word, but we can use other words that contain it, like "class_name", or "klass" to work around this.

We can use the regex anchor \b which represents word boundaries.

string = <<-STRING
The word class is a reserved word,
but we can use other words that
contain it, like "class_name", or
"klass" to work around this.
STRING

pattern = /\b[ck]lass\b/

string.scan(pattern)
#=> ["class", "klass"]

From the guide to word boundaries on regular-expressions.info (an excellent reference):

There are three different positions that qualify as word boundaries:

Check out the regex docs section on anchors for Ruby specific detail.

Return to Flashcard Results