Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: add boundaries \b option when using Regexp.union (array)?

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|,....../
like image 849
L457 Avatar asked Jul 13 '26 10:07

L457


2 Answers

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" })
like image 154
Amadan Avatar answered Jul 15 '26 04:07

Amadan


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/
like image 21
Pramod Shinde Avatar answered Jul 15 '26 02:07

Pramod Shinde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!