I am creating a regex matcher using:
Regexp.new(Regexp.union(some_hash.keys))
is it possible to add a boundaries filter to each element of the array so I have:
/\bkey1\b|\bkey2\b|,....../
For regexp keys:
Regexp.union(some_hash.keys.map { |k| /\b#{k}\b/ })
or for literal keys:
Regexp.union(some_hash.keys.map { |k| /\b#{Regexp.escape(k)}\b/ })
The result of Regexp.union is already a Regexp, no need for Regexp.new. In fact, we can also use plain strings inside Regexp.union, the difference being we don't initialise the flags in each subexpression:
Regexp.union(some_hash.keys.map { |k| "\\b#{k}\\b" })
Regexp.union(some_hash.keys.map { |k| "\\b#{Regexp.escape(k)}\\b" })
You can generate regex in simplest way without using Regexp as
hash = {'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4}
/\b#{hash.keys.join('\b|\b')}\b/
=>/\ba\b|\bb\b|\bc\b|\bd\b/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With