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:
- Positive lookahead
- Negative lookahead
- Positive lookbehind
- Negative lookbehind
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