[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Chopping the beginning of a string elegantly
From:       Kero <kero () chello ! single-dot ! nl>
Date:       2005-07-29 12:56:01
Message-ID: slrndek9mj.3sl.kero () chmeee ! m38c ! nl
[Download RAW message or body]

> I'm having some trouble finding an elegant way of removing a part of a
> string based on an pattern.

str = "BeginOfString"
str[/Begin/]    => "Begin"
str[/Of/]       => "Of"

if you want to restrict it to the beginning, do

str[/^Begin/]   => "Begin"
str[/^Of/]      => nil

and then for replacing it, or removing it

str[/^Begin/] = ""   => ""
str                  => "OfString"
str[/Of/] = "a"      => "a"
str                  => "aString"

For lots more of information on patterns, read the regexp chapter of the
pickaxe.

hth,
Kero.

+--- Kero ------------------------- kero@chello@nl ---+
|  all the meaningless and empty words I spoke        |
|                       Promises -- The Cranberries   |
+--- M38c --- http://members.chello.nl/k.vangelder ---+

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic