How to create case insensitive Regexp from case insensitive Regexp?

Given the hash of the regexes defined with the forward slash ( '/'

), I would like to check if the string matches any of them.

My match should be case insensitive, but I don't want to explicitly use the flag i

at the end of the regexps in my hash.

str="ENTITY foo is END"

kw={
 ent: /entity/,
 end: /end/
}

kw.each do |kw_id,rex|
  p rex.match(str)
end

      

This is not the case, because they rex

don't make case insensitive (of course, just adding 'i'

to the end of my regex would do the trick, but that's not what I want).

So, I changed my code as follows to create a new regexp:

kw.each do |kw_id,rex|
  rexi=Regexp.new(rex.to_s,true)
  p rexi.match(str)
end

      

But then again, this cannot recognize any part of the string.

So how do I create case insensitive from case insensitive Regexp?

+3


source to share


1 answer


To add a case-insensitive "ignore case" option:

original = /abc/
insensitive = Regexp.new(
                original.source, 
                original.options | Regexp::IGNORECASE)

      

To make a case-insensitive match without using the "ignore" option, a possible solution is to create a regular expression that matches uppercase and lowercase letters as follows:

original = /abc/ 
insensitive = /[Aa][Bb][Cc]/

      



If your original regexes are all letters as in your examples, you can automate the following:

original = /abc/
insensitive = Regexp.new(
                original.source.gsub(/[[:alpha:]]/){ "[#{$&.upcase}#$&]" })

      

If your original regular expressions are more than just letters, you need more sophisticated automation. For example, if your original regex uses curly braces, character classes, named entries, etc., then you need code that respects them. (Thanks to hobbs in the comments to highlight this)

+3


source







All Articles