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]:

There are three different positions that qualify as word boundaries:

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

[regex docs section on anchors]: http://ruby-doc.org/core-2.1.1/Regexp.html#class-Regexp-label-Anchors [word boundaries on regular-expressions.info]: http://www.regular-expressions.info/wordboundaries.html

Return to Flashcard Results