From: Robert Klemme Date: 2011-03-12T00:58:46+09:00 Subject: Re: substitution in a regular expression On Fri, Mar 11, 2011 at 2:39 PM, Mario Ruiz wrote: > I want to replace the text for fecha on the string but I don't know how > to do it: > > > a=" id:'name', >  label :'Name', >  type:'string', > idx : 3, > fecha: 24/13/2009, > whitelabel:'true', > fecha: 11/01/2009" > > > the regular expression I'm using is: > /'?fecha'? *: *'(.*)' *, *$/ > > and the result I want is: > a=" id:'name', >  label :'Name', >  type:'string', > idx : 3, > fecha: 01/03/2010, > whitelabel:'true', > fecha: 01/03/2010" Two ways: irb(main):004:0> a=" id:'name', irb(main):005:0" label :'Name', irb(main):006:0" type:'string', irb(main):007:0" idx : 3, irb(main):008:0" fecha: 24/13/2009, irb(main):009:0" whitelabel:'true', irb(main):010:0" fecha: 11/01/2009" => " id:'name',\n label :'Name',\n type:'string',\nidx : 3,\nfecha: 24/13/2009,\nwhitelabel:'true',\nfecha: 11/01/2009" irb(main):011:0> a[/^fecha:\s*(\S+)/, 1] = "REPLACED" => "REPLACED" irb(main):012:0> a => " id:'name',\n label :'Name',\n type:'string',\nidx : 3,\nfecha: REPLACED\nwhitelabel:'true',\nfecha: 11/01/2009" irb(main):013:0> a.gsub(/^(fecha:\s*)\S+/) {$1+"ANOTHER_REPLACED"} => " id:'name',\n label :'Name',\n type:'string',\nidx : 3,\nfecha: ANOTHER_REPLACED\nwhitelabel:'true',\nfecha: ANOTHER_REPLACED" Note, that the first approach only replaces one occurrence. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/