检查字符串是否包含散列中的任何键以及 return 它包含的键的值
Check if a string includes any of the keys in a hash and return the value of the key it contains
我有一个包含多个键的散列和一个字符串,其中包含 none 或散列中的一个键。
h = {"k1"=>"v1", "k2"=>"v2", "k3"=>"v3"}
s = "this is an example string that might occur with a key somewhere in the string k1(with special characters like (^&*$#@!^&&*))"
检查 s
是否包含 h
中的任何键以及如果包含,return 它包含的键的值的最佳方法是什么?
例如,对于上述h
和s
的例子,输出应该是v1
。
编辑:只有字符串是用户定义的。哈希将始终相同。
从哈希 h
键和 match
字符串中创建一个正则表达式:
h[s.match(/#{h.keys.join('|')}/).to_s]
# => "v1"
或者按照 Amadan 的建议使用 Regexp#escape 以确保安全:
h[s.match(/#{h.keys.map(&Regexp.method(:escape)).join('|')}/).to_s]
# => "v1"
如果字符串 s
均匀分布,我们也可以这样做:
s = "this is an example string that might occur with a key somewhere in the string k1 (with special characters like (^&*$\#@!^&&*))"
h[(s.split & h.keys).first]
# => "v1"
我觉得这种方式可读:
hash_key_in_s = s[Regexp.union(h.keys)]
p h[hash_key_in_s] #=> "v1"
或一行:
p h.fetch s[Regexp.union(h.keys)] #=> "v1"
这是一个不使用正则表达式的版本:
p h.fetch( h.keys.find{|key|s[key]} ) #=> "v1"
我有一个包含多个键的散列和一个字符串,其中包含 none 或散列中的一个键。
h = {"k1"=>"v1", "k2"=>"v2", "k3"=>"v3"}
s = "this is an example string that might occur with a key somewhere in the string k1(with special characters like (^&*$#@!^&&*))"
检查 s
是否包含 h
中的任何键以及如果包含,return 它包含的键的值的最佳方法是什么?
例如,对于上述h
和s
的例子,输出应该是v1
。
编辑:只有字符串是用户定义的。哈希将始终相同。
从哈希 h
键和 match
字符串中创建一个正则表达式:
h[s.match(/#{h.keys.join('|')}/).to_s]
# => "v1"
或者按照 Amadan 的建议使用 Regexp#escape 以确保安全:
h[s.match(/#{h.keys.map(&Regexp.method(:escape)).join('|')}/).to_s]
# => "v1"
如果字符串 s
均匀分布,我们也可以这样做:
s = "this is an example string that might occur with a key somewhere in the string k1 (with special characters like (^&*$\#@!^&&*))"
h[(s.split & h.keys).first]
# => "v1"
我觉得这种方式可读:
hash_key_in_s = s[Regexp.union(h.keys)]
p h[hash_key_in_s] #=> "v1"
或一行:
p h.fetch s[Regexp.union(h.keys)] #=> "v1"
这是一个不使用正则表达式的版本:
p h.fetch( h.keys.find{|key|s[key]} ) #=> "v1"