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:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
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