From: Tim Greer Date: 2009-01-28T04:47:46+09:00 Subject: Re: A bug in Ruby regexp lib? Tim Greer wrote: > Artc5abras c5a0lajus wrote: > >> ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux] >> >> x11@www:~$ irb >> irb(main):001:0> s = "www.myspace.com/djmamania >> www.myspace.com/djmantini" >> => "www.myspace.com/djmamania www.myspace.com/djmantini" >> irb(main):002:0> s1 = s.gsub(%r{(\s|^)(www\..*?)(\s|$)}m, '\1> href="http://\2">\2\3') >> => "> > href=\"http://www.myspace.com/djmamania\">www.myspace.com/djmamania >> www.myspace.com/djmantini" >> irb(main):003:0> s1.gsub(%r{(\s|^)(www\..*?)(\s|$)}m, '\1> href="http://\2">\2\3') >> => "> > href=\"http://www.myspace.com/djmamania\">www.myspace.com/djmamania >> > > href=\"http://www.myspace.com/djmantini\">www.myspace.com/djmantini" >> >> Why I have to call gsub two times for this to work? Same regexp works >> fine in Firefox JS :) > > Did you mean: > > s1 = s.gsub(%r{(^|\s)?(www\..*?)(\s|$)}m, '\1 href="http://\2">\2\3') > > irb(main):035:0> s1 = s.gsub(%r{(^|\s)?(www\..*?)(\s|$)}m, '\1 href="http://\2">\2\3') > => " href=\"http://www.myspace.com/djmamania\">www.myspace.com/djmamania > href=\"http://www.myspace.com/djmantini\">www.myspace.com/djmantini" > > Note the \1 is using (^|\s), as it's either the start of the string > (^) or a white space between the two URLs (\s), but you also have \3, > which is either the end of the string ($) or white space between the > URLs (or following) (\s), and since there's only one white space > between the two URLs, it throws is off. > > To account for both \1 and \3, above I've set it to be optional > (^|\s)? > because this will allow you to use \3 without is breaking it. There > are other ways to do this, but just working with what you were using, > that's a change you could make to get the desired results on the first > one... unless I misunderstood what you were trying to do? Geez, pardon the typos I've made above. Apparently I'm having trouble working my keyboard (some of those "is" should be "it") -- Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc. Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers and Custom Hosting. 24/7 support, 30 day guarantee, secure servers. Industry's most experienced staff! -- Web Hosting With Muscle!