mystery regexp

S

Steve Throckmorton

I found this regexp in the docs for the OptionParser class, and I don't
understand it. Google hasn't helped, nor has the Pickaxe, so I thought
I would ask here. The purpose of the code is to ensure that a file
extension submitted by the user begins with a period (a dot).

file_ext.sub!(/\A\.(?=.)/, ".")

I understand all except (?=.) As far as I can tell the regexp works
fine without it. I can delete the dot inside the parens, and the code
still runs. I can change the = to a - and the code runs, but if I
substitute a letter or a * instead, it doesn't.

Someone please clue me in here. What is this thing?
 
J

Jason Sweat

I found this regexp in the docs for the OptionParser class, and I don't
understand it. Google hasn't helped, nor has the Pickaxe, so I thought
I would ask here. The purpose of the code is to ensure that a file
extension submitted by the user begins with a period (a dot).

file_ext.sub!(/\A\.(?=.)/, ".")

I understand all except (?=.) As far as I can tell the regexp works
fine without it. I can delete the dot inside the parens, and the code
still runs. I can change the = to a - and the code runs, but if I
substitute a letter or a * instead, it doesn't.

Someone please clue me in here. What is this thing?

\A start of subject (independent of multiline mode)

(?= is a positive look ahead assetion

so \A the begining of the input \. is a literal . (and there must be
something more than that afterwords.

$ irb=> #<MatchData:0x409866a8>
 
J

James Edward Gray II

file_ext.sub!(/\A\.(?=.)/, ".")

I understand all except (?=.)

That's a look-ahead assertion, ensuring there is at least one
character following the period. Observe:
=> nil

Hope that helps.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top