substitution in a regular expression

M

Mario Ruiz

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"
 
A

Andrew Wagner

[Note: parts of this message were removed to make it a legal post.]

I played with your regex on rubular, and came up with this as one possible
solution:

http://www.rubular.com/r/LBaUQqW7SL

But there are a number of possibilities, depending on exactly what you want
to do.
 
G

Gunther Diemant

[Note: parts of this message were removed to make it a legal post.]

Try a.gsub(/'?fecha'?\s*:\*[0-9\/]+/, "fecha: 01/03/2011").
 
R

Robert Klemme

I want to replace the text for fecha on the string but I don't know how
to do it:


a=3D" id:'name',
=A0label :'Name',
=A0type:'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=3D" id:'name',
=A0label :'Name',
=A0type:'string',
idx : 3,
fecha: 01/03/2010,
whitelabel:'true',
fecha: 01/03/2010"

Two ways:

irb(main):004:0> a=3D" 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"
=3D> " 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] =3D "REPLACED"
=3D> "REPLACED"
irb(main):012:0> a
=3D> " 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"}
=3D> " 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

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top