RubyNoobie
RubyNoobie

Reputation: 685

How to `look behind` regex in Ruby?

I am confused why in the following examples #2 does not work and #3 works.

 #1. get `o` if immediately preceded by J
"Jones Bond".scan(/(?<=J)o/) #=> o

 #2. get `o` if preceded by J anywhere. Since `J` occurs once I am using `+`
"James Bond".scan(/(?<=J)+o/) #=> []  empty

 #3. get `o` if preceded by J anywhere zero or more times by using `*`
"James Bond".scan(/(?<=J)*o/) #=> o

I translate lookbehind as left-to-right and lookahead as right-to-left to remember easily. Is it correct?

Upvotes: 0

Views: 460

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

The second example doesn't work cause you have to use a fixed size string when you lookbehind. You can do instead:

puts "James Bond".scan(/(J.*)(o)/)[0][1]

J.* - means 'J' followed by any number of characters - which takes the array of the results ([0]) and returns the second group ([1])

As for #3, ,since you want to find 'o' if preceded by 'J' zero or more times, you don't have to use lookbehind at all, just search for 'o':

"James Bond".scan(/(o)/)

Upvotes: 1

Related Questions