Given the following sample, how could we define a pattern that would capture the keys in this hash string, without including the colon?
sample = \
"{ count: 2, title: 'Hello', section: 3 }"
We can use a "lookahead" that asserts that a colon follows our match. In this
case we use a "Positive lookahead assertion" which has the form (?=pat)
,
where our pattern is :
.
sample = \
"{ count: 2, title: 'Hello', section: 3 }"
sample.scan(/\w+(?=:)/)
#=> ["count", "title", "section"]
Lookaheads are another type of anchor like ^
or \b
, and like other anchors
they are "zero-width". This means whatever matches the anchor will not be
included in the match output.
There are four "lookaround" anchors:
Check out the [regex docs section on anchors][] for more detail.
[regex docs section on anchors]: http://ruby-doc.org/core-2.1.1/Regexp.html#class-Regexp-label-Anchors
Return to Flashcard Results