Tom Cloyd
2/11/2009 4:44:00 AM
badboy wrote:
> Jon Garvin schrieb:
>
>> I've got the following string...
>>
>> "This is ( a test"
>>
>> And I want to do a regex gsub on it to turn it into...
>>
>> "This is \( a test"
>>
>> In irb, If I start with...
>>
>> "This is ( a test".gsub(/[\(]/,'\&') => "This is ( a test"
>>
>> And then progressively added more backslashes, I get the following
>> results, none of which are what I'm looking for. The second one is,
>> IMO, the one that should work.
>>
>> "This is ( a test".gsub(/[\(]/,'\\&') => "This is ( a test"
>> "This is ( a test".gsub(/[\(]/,'\\\&') => "This is \\& a test"
>> "This is ( a test".gsub(/[\(]/,'\\\\&') => "This is \\& a test"
>> "This is ( a test".gsub(/[\(]/,'\\\\\&')=> "This is \\( a test"
>>
>>
>> Am I just having a serious case of the mondays, or is there a bug in how
>> Ruby deals with \ characters when trying to represent an actual single >> character?
>>
>> I'm using ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]
>>
>>
> you know Regexp.escape ?
>
>
>
Yikes...thanks for the reminder. I always seem to find 6 hard ways to do
something before learning (and occasionally discovering) an easy way.
Regexp.escape solve LOTS of problems quickly. ~t.
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@tomcloyd.com >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~