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
endirb(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:
It IS greedy: In your case it starts at the beginning, matches as many
digits as it can (zero) and returns the match. 'Greedy' means it will
match as many as it can from the start of the match, not that it will
look to find the largest match. Since your regexp is \d* it means it can
match zero digits.
Programming Ruby: The Pragmatic Programmer's Guide
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]