regexp indexes to strings

R

Rob Partington

I like this, but can it be extended to work for replacing?

irb(main):001:0> a="123-456-1239"
=> "123-456-1239"
irb(main):002:0> a[/123/]
=> "123"
irb(main):003:0> a[/123/]="xxx"
=> "xxx"
irb(main):004:0> a
=> "xxx-456-1239"

This is good stuff. Except it doesn't extend.

irb(main):005:0> a="123-456-1239"
=> "123-456-1239"
irb(main):006:0> a[/123/, 2]="xxx"
IndexError: index 2 out of regexp
from (irb):6:in `[]='
from (irb):6
irb(main):007:0> a[/123/, 1]="xxx"
IndexError: index 1 out of regexp
from (irb):7:in `[]='
from (irb):7
irb(main):008:0> a
=> "123-456-1239"

Bah! This would really rule.
 
T

ts

R> irb(main):006:0> a[/123/, 2]="xxx"
R> IndexError: index 2 out of regexp

Well, this case is for

svg% ruby -e 'a="123-456-1239"; a[/1(2)3/, 1] = "xxx"; p a'
"1xxx3-456-1239"
svg%

svg% ruby -e 'a="123-456-1239"; a[/1(2)(3)/, 2] = "xxx"; p a'
"12xxx-456-1239"
svg%

you can write

svg% ruby -e 'a="123-456-1239"; a[/123/] = "xxx"; p a'
"xxx-456-1239"
svg%
 
Y

Yan-Fa Li

I think it doesn't work because your regexp only has one capture group.
If you
define multiple capture groups it works just fine:

a="123-456-1239"
a[/([0-9]{3,3})-([0-9]{3,3})-([0-9]{3,4})/,2]="XXX"

I tested this in IRB and it seems work just fine. I don't know if
there's a more efficient way to do
this that is less complex looking but it does work. Let me know if you
need help decoding this regexp,
but I think it's fairly self explanatory.

Yan
 

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,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top