[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Variable substitution in a regex

Steve Callaway

5/18/2005 12:53:00 PM

Yeah, straightforward enough, moreover you can process
an array of vars as in the snippet I put up on
Rubyforge:

# function to regexp vars
def is_element_in_string?(in_string, in_array)
in_array.each do |line|
rx_test = /#{line}/
if in_string =~ rx_test
return true
end
end
return false
end

# as an example we may wish to see whether a list of
football match results
# contains a result of a team we are interested in
varray = Array.new
# now populate the array with reegxps you wish to
match...
varray = ["Plymouth Argyle", "Blackburn Rovers" ,
"Manchester .*", "Tott.*"]

#Examples:
results = "Plymouth Argyle 5 - Cardiff 0"
puts is_element_in_string?(results, varray)
#=> true

results = "Watford 3 - Sunderland 0"
puts is_element_in_string?(results, varray)
#=> false, no match


results = "Man City 2 - Man Utd 0"
puts is_element_in_string?(results, varray)
#=> false
# since it obviously won't regexp unless we add "Man
U.*" to our array...
# e.g.
varray.push("Man U.*")
puts is_element_in_string?(results, varray)
# => true


--- Scott Pack <softwarespack@yahoo.com> wrote:
> Hi,
>
> I am new to Ruby. Can I substitute the value of a
> variable into a regular expression? For example:
>
> exp = /(\d+)/ #works
> exp = /(\d+)/ + 'some string value' #Not!
>
> Thanks,
>
> S
>
>
>
>
> __________________________________
> Yahoo! Mail Mobile
> Take Yahoo! Mail with you! Check email on your
> mobile phone.
> http://mobile.yahoo.com/...
>
>



__________________________________
Do you Yahoo!?
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/...


1 Answer

dblack

5/18/2005 1:19:00 PM

0