Matching regular expression

I have a string that contains a list of keys and values.

"key1: a_value, key2: another_value, key3: yet_another_value"

I have an array of ["key1", "key2", "key3"].

I'd like to loop through and find all the values in the string that
have a key in the key array.

My first attempt was:

keys = ["key1", "key2", "key3"]
my_str = "key1: a_value, key2: another_value, key3: yet_another_value"
keys.each do |key|
    my_str =~ Regexp.new("#{key}: \\w+")
    puts "the value for #{key} was #{$1}"
end

But that's not working properly.

Any ideas?

Thanks,
Joe

Joe Van Dyk wrote:

I have a string that contains a list of keys and values.

"key1: a_value, key2: another_value, key3: yet_another_value"

I have an array of ["key1", "key2", "key3"].

I'd like to loop through and find all the values in the string that
have a key in the key array.

My first attempt was:

keys = ["key1", "key2", "key3"]
my_str = "key1: a_value, key2: another_value, key3: yet_another_value"
keys.each do |key|
    my_str =~ Regexp.new("#{key}: \\w+")

use this instead
       my_str =~ Regexp.new("#{key}: (\\w+)")
you need the brackets in order to capture the substring

    puts "the value for #{key} was #{$1}"
end

But that's not working properly.

Any ideas?

HTH

···

--
Mark Sparshatt

My first attempt was:

[snip]

But that's not working properly.

Any ideas?

try this

Simon-Strandgaards-computer:~/code/experiments/ruby simonstrandgaard$
ruby re1.rb
the value for key1 was a_value
the value for key2 was another_value
the value for key3 was yet_another_value
Simon-Strandgaards-computer:~/code/experiments/ruby simonstrandgaard$
expand -t2 re1.rb
keys = ["key1", "key2", "key3"]
my_str = "key1: a_value, key2: another_value, key3: yet_another_value"
res = my_str.scan(/(\w+):\s(\w+)/)
res.each do |key, val|
  puts "the value for #{key} was #{val}"
end
Simon-Strandgaards-computer:~/code/experiments/ruby simonstrandgaard$

···

On Tue, 8 Mar 2005 06:04:48 +0900, Joe Van Dyk <joevandyk@gmail.com> wrote:

--
Simon Strandgaard

Argh, you're right. Thanks.

···

On Tue, 8 Mar 2005 06:13:24 +0900, mark sparshatt <msparshatt@yahoo.co.uk> wrote:

Joe Van Dyk wrote:
> I have a string that contains a list of keys and values.
>
> "key1: a_value, key2: another_value, key3: yet_another_value"
>
> I have an array of ["key1", "key2", "key3"].
>
> I'd like to loop through and find all the values in the string that
> have a key in the key array.
>
> My first attempt was:
>
> keys = ["key1", "key2", "key3"]
> my_str = "key1: a_value, key2: another_value, key3: yet_another_value"
> keys.each do |key|
> my_str =~ Regexp.new("#{key}: \\w+")

use this instead
       my_str =~ Regexp.new("#{key}: (\\w+)")
you need the brackets in order to capture the substring

> puts "the value for #{key} was #{$1}"
> end
>
> But that's not working properly.
>
> Any ideas?

HTH