The '^' in the regular expression above is an anchor to the beginning of
the string.
Also perhaps a similar strategy if I would want to remove something
from the middle or the end?
Just leave the '^' out of the regular expression from above. If you want
to remove at the end, put a '$' at the end of your regular expression.
···
On Fri, July 29, 2005 8:41 am, francisrammeloo@hotmail.com said:
--
Jason Voegele
"There is an essential core at the center of each man and woman that
remains unaltered no matter how life's externals may be transformed
or recombined. But it's smaller than we think."
-- Gene Wolfe, The Book of the Long Sun
With all the different responses you've received, it's obvious that the
Perl mantra "There's More Than One Way To Do It" also holds true with
Ruby.
···
On Fri, July 29, 2005 8:41 am, francisrammeloo@hotmail.com said:
Hi all,
I'm having some trouble finding an elegant way of removing a part of a
string based on an pattern.
Suppose I want to chop off the "Begin" in the string "BeginCaption".
--
Jason Voegele
"There is an essential core at the center of each man and woman that
remains unaltered no matter how life's externals may be transformed
or recombined. But it's smaller than we think."
-- Gene Wolfe, The Book of the Long Sun
but what you asked was perhaps more like this:
irb(main):004:0> widgetdescription='BeginCaption'
=> "BeginCaption"
irb(main):005:0> (thePane=widgetdescription).slice!(/^Begin/)
=> "Begin"
irb(main):006:0> thePane
=> "Caption"
if there is no match:
irb(main):007:0> widgetdescription='EndCaption'
=> "EndCaption"
irb(main):008:0> (thePane=widgetdescription).slice!(/^Begin/) or warn "no match"
no match
=> nil
irb(main):009:0> thePane
=> "EndCaption"
or perhaps:
irb(main):010:0> thePane=/^Begin(.*)/.match(widgetdescription)[1]
=> "Caption"
(but that goes wrong if there is no ^Begin)
" BeginCaption 0, 20, 66, .."
(the whitespace can be a combination of tabs and spaces)
So I actually have to cut out "Caption" word in the <<middle>> of the
string.
Brian's hint got me on the right track. The solution I finally found
was:
pane = line.sub(/\s*Begin(\w+).*/, '\1')
Unless some expert can prove a still more tight solution I believe I
have found the best way to cut out the "Caption" part of the string.
Thank you all for your help.
Best regards,
Francis
Hmm. A wild guess (e.g. until there's a Windows installer for Ruby 1.9 w/
Oniguruma, or someone makes a SuSE compatible RPM for that) is that lookbehinds
in REs could reduce that to:
pane = line[/(?<=Begin)\w+/]
There's a 95% chance you don't need those groups to catch the initial whitespace
and consume the rest of the string, so:
pane = line.match(/Begin(\w+)/)[1]
also works and has a bit less noise. Weirdly though, Benchmark tells me it's
slightly slower. Guess you can't have your cake and eat it.