Help! My positive lookbehind doesn't work!

Given a variable s containing a string, which might contain an
underscore, I would like to extract the character AFTER the underscore.
I thought this is easy:

after = s[/($<=_)./]

But this returns nil all the time. Indeed, I see that, for example,

‘ab_cd’ =~ /($<=_)./

doesn’t match. Could it be that I don’t understand the proper usage of
positive lookbehind?

=========================================

SOLVED! As B.Onzo pointed out, I had wrong syntax. The correct statement
would be

after = s[/(?<=_)./]

Hey Ronald,

Maybe with you could get away with just using the ‘split’ method. Could
you try the following code & see if it works for your use case?

##########
s = ‘ab_cd’
s.split(’_’).last
##########

If you only want one character after the underscore:

##########
s = ‘ab_cd’
s.split(’_’).last[0]
##########

Another alternative:
(I’m assuming you want the whole string if there is no underscore)

##########
match = string.match(/\w*_(.)/)
character_or_string = match ? match[1] : string
##########

Let me know if that helps :slight_smile:

  • Jesus Castello, blackbytes.info

Ronald F. wrote in post #1185221:

Given a variable s containing a string, which might contain an
underscore, I would like to extract the character AFTER the underscore.
I thought this is easy:

after = s[/($<=_)./]

But this returns nil all the time. Indeed, I see that, for example,

‘ab_cd’ =~ /($<=_)./

doesn’t match. Could it be that I don’t understand the proper usage of
positive lookbehind?

Maybe, but you aren’t using any positive lookbehind, that would be
(?<=xxx) with a ?

Jesus Castello wrote in post #1185225:

Maybe with you could get away with just using the ‘split’ method.

Of course, this is possible. Actually, as a temporary solution, I used a
regexp, similar to your solution with ‘match’.

However, I thought that this should be possible to solve with a
lookbehind, and would like to use this feature. I’m searching that part
of a string, which comes AFTER a certain pattern. Shouldn’t this be a
canonical example for “positive lookbehind”?

Ronald

B. Onzo wrote in post #1185235:

Maybe, but you aren’t using any positive lookbehind, that would be
(?<=xxx) with a ?

Arrrgh!!! You are right, what silly mistake. Indeed, if I replace the
dollar by a question mark, it works!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs