Ruby Regex Key Search

Ruby regex key search

I would advise extending Hash with a new method instead of replacing has_key?.

class Hash
def has_rkey?(search)
search = Regexp.new(search.to_s) unless search.is_a?(Regexp)
!!keys.detect{ |key| key =~ search }
end
end

This will work with strings, symbols or a regexp as arguments.

irb> h = {:test => 1}
 => {:test=>1}  
irb> h.has_rkey?(:te)
=> true
irb> h.has_rkey?("te")
=> true
irb> h.has_rkey?(/te/)
=> true
irb> h.has_rkey?("foo")
=> false
irb> h.has_rkey?(:foo)
=> false
irb> h.has_rkey?(/foo/)
=> false

How to see if string matches any regex keys in ruby hash

The solution ended up being, based on other answers for the opposite case:

val = myhash.keys.select {|key| message.to_s.match(key)}

Regex to find a key in a string w Rails Ruby?

Why not just replace "human_id_" with ""? No need to do regexp for that:

theId = key.gsub("human_id_", "")

How can I use a regex match as a hash index in Ruby?

Try this

assessment.gsub(/#{farm.keys.join('|')}/, farm)

Ruby regular expression to extract key values

Agree with John Watts comment. Use something like nokogiri to parse XML - it is a breeze. If you still want to stick with regex parsing you could do something like:

str.split(' ').map{ |part| part.match( /(.+)="(.+)"/ )[1..2] }

and you will get results as below:

> str = "type=\"text/xsl\" href=\"http://skdjf.sdjhshf/CDA0000=.xsl\""
=> "type=\"text/xsl\" href=\"http://skdjf.sdjhshf/CDA0000=.xsl\""

> str2 = "href=\"http://skdjf.sdjhshf/CDA0000=.xsl\" type=\"text/xsl\""
=> "href=\"http://skdjf.sdjhshf/CDA0000=.xsl\" type=\"text/xsl\""

> str.split(' ').map{ |part| part.match( /(.+)="(.+)"/ )[1..2] }
=> [["type", "text/xsl"], ["href", "http://skdjf.sdjhshf/CDA0000=.xsl"]]

> str2.split(' ').map{ |part| part.match( /(.+)="(.+)"/ )[1..2] }
=> [["href", "http://skdjf.sdjhshf/CDA0000=.xsl"], ["type", "text/xsl"]]

that you can put in a hash or wherever wou want to have it.

With nokogiri you can get hold of a node and then do something like node['href'] in your case. Probably much easier.

Ruby 1.9 regex as a hash key

It will not work without some extra code, as it is you are comparing a Regexp object with either an Integer or a String object. They won't be value equal, nor identity equal. They would match but that requires changes to the Hash class code.

irb(main):001:0> /(\d+)/.class
=> Regexp
irb(main):002:0> 2222.class
=> Fixnum
irb(main):003:0> '2222'.class
=> String
irb(main):004:0> /(\d+)/==2222
=> false
irb(main):007:0> /(\d+)/=='2222'
=> false
irb(main):009:0> /(\d+)/.equal?'2222'
=> false
irb(main):010:0> /(\d+)/.equal?2222
=> false

you would have to iterate the hash and use =~ in something like:

 hash.each do |k,v|    
unless (k=~whatever.to_s).nil?
puts v
end
end

or change the Hash class to try =~ in addition to the normal matching conditions. (I think that last option would be difficult, in mri the Hash class seems to have a lot of C code)

Ruby Regex filter based on two hashes

I assume @allowed should be as follows. If the last key does not begin with "instrument." or ".labels" is present, the purpose of the wildcard "*" is not clear.

@allowed = { "timestamp"=>true, "event.type"=>true,
"instrument.network.*"=>true }

arr = @allowed.map { |k,_|
Regexp.new(k.gsub('.', '\.').sub('*', '.*')) }
#=> [/timestamp/, /event\.type/, /instrument\.network\..*/]
r = /\A#{Regexp.union(arr)}\z/
#=> /\A(?-mix:(?-mix:timestamp)|(?-mix:event\.type)|(?-mix:instrument\.network\..*))\z/
metadata.select do |k,_|
res = k.match?(r)
puts "#{k} is allowed?: #{res}"
res
end
event.type is allowed?: true
instrument.network.one is allowed?: true
instrument.network.two is allowed?: true
other.meta is allowed?: false
#=> {"event.type"=>"message", "instrument.network.one"=>false, ]
# "instrument.network.two"=>false}

Ruby replace hash key using a Regex

Detect column names in a separate step. Intermediate mapping will look like {"A"=>:date, "B"=>:portfolio_name, "C"=>:currency}, and then you can transform data array.

This is pretty straightforward:

header_mapping = header.transform_values{|v|
mapping.find{|key,regex| v.match?(regex) }&.first || raise("Unknown header field #{v}")
}

rows.map{|row|
row.transform_keys{|k| header_mapping[k].to_s }
}

Code requires Ruby 2.4+ for native Hash#transform_* or ActiveSupport



Related Topics



Leave a reply



Submit