regular expression seems broken not greedy when it should be

C

CarlosRivera

I am very new to ruby. I was working my way through the tutorials.
However, it looks like the regular expressions seem broken; however,
since I am so new to ruby it could be me. It would appear that the
regular expressions are not greedy.

I have the following code:

def showRE(a,re)

startMarker = "<<<"
endMarker = ">>>"

if a =~ re
"#{$`}#{startMarker}#{$&}#{endMarker}#{$'}"
else
"no match for '#{a}'"
end
end


irb(main):012:0> showRE("abc123def", /\d*/)
=> "<<<>>>abc123def"
irb(main):013:0> showRE("abc123def", /\d+/)
=> "abc<<<123>>>def"
irb(main):014:0>

I thought that normally * was greedy and would try to match the largest
string and not the tiniest. If this is the case the "<<<" and ">>>"
should be around the number "123" in the output for the first attempt
similar to the second function call. In the ruby docs, it states at the
following URL:

http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UL

The following:

re ?

Matches zero or one occurrence of re. The *, +, and {m,n} modifiers are
greedy by default. Append a question mark to make them minimal.

Did I misinterpret something? My ruby information:

ruby 1.8.1 (2003-12-25) [i386-openbsd3.5]
 
S

Simon Strandgaard

On Monday 20 September 2004 09:54, CarlosRivera wrote:
[snip]
I thought that normally * was greedy and would try to match the largest
string and not the tiniest. If this is the case the "<<<" and ">>>"
should be around the number "123" in the output for the first attempt
[snip]

Regexp usualy follows the left-most-longest rule..
in your case the longest expression * can find is the empty string.
 

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

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top