Forum: Ruby Ruby Regex

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F16e67cf8c0d59e1b98f5ba46d84b31d?d=identicon&s=25 Sriram Varahan (sriram)
on 2009-05-06 09:18
Hello,


  I have this string:

    "d:\\home\\abc2.zip\\abc.zip\\abc.com"

  I need to extract the contents up to the first occurrence of zip which
would be:

  "d:\\home\\abc2.zip"

When i use a regex like: \(.+).zip\ it gives me the entire contents upto
the second zip.

 "d:\\home\\abc2.zip\\abc.zip" which is not what I am looking for.

Any solution to this?

Thanks.
Sriram.
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2009-05-06 09:34
(Received via mailing list)
On Wed, May 6, 2009 at 9:18 AM, Sriram Varahan
<sriram.varahan@gmail.com> wrote:
>  "d:\\home\\abc2.zip"
>
> When i use a regex like: \(.+).zip\ it gives me the entire contents upto
> the second zip.
Why are you so greedy Sriram ;)? Well it is not you it is the "+"
which is greedy, try the non greedy version "+?" it might just give
you a nice surprise.
R.
F16e67cf8c0d59e1b98f5ba46d84b31d?d=identicon&s=25 Sriram Varahan (sriram)
on 2009-05-06 09:46
Was definitely a nice surprise! Thanks Robert for your help :)
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-05-06 13:04
(Received via mailing list)
2009/5/6 Robert Dober <robert.dober@gmail.com>:
>>
>>  "d:\\home\\abc2.zip"
>>
>> When i use a regex like: \(.+).zip\ it gives me the entire contents upto
>> the second zip.
> Why are you so greedy Sriram ;)? Well it is not you it is the "+"
> which is greedy, try the non greedy version "+?" it might just give
> you a nice surprise.

Why not use File.dirname?

irb(main):003:0> File.dirname "d:\\home\\abc2.zip\\abc.zip\\abc.com"
=> "d:\\home\\abc2.zip\\abc.zip"

Cheers

robert
1e736afdcdfe0753d67a81d449aca590?d=identicon&s=25 Srijayanth Sridhar (Guest)
on 2009-05-06 13:08
(Received via mailing list)
He only wanted the first occurrence of zip I think.

Jayanth
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-05-06 13:54
(Received via mailing list)
2009/5/6 Srijayanth Sridhar <srijayanth@gmail.com>:
> He only wanted the first occurrence of zip I think.

Ah, yes.  I overlooked that. Sorry for the noise.

IMHO an anchor is in order:

irb(main):001:0> "d:\\home\\abc2.zip\\abc.zip\\abc.com"[/\A.*?\.zip/]
=> "d:\\home\\abc2.zip"

Cheers

robert
This topic is locked and can not be replied to.