LearningBasics
LearningBasics

Reputation: 680

Ruby on Rails: Unable to retrieve regex from database

I have set of regexes which I stored in some table in DB. I retrieve them and apply some operation using those regexes but they are not working as desired.

junkremoveregex=[]
    regexes = JunkRemoveLineRegex.find(:all,:select => 'regex')

    regexes.each do |regex|
      junkremoveregex << regex.regex
    end

    puts junkremoveregex

    junktest=/note/

    junkremoveregexset=Regexp.union(junkremoveregex)
    line ="note thhat yo yo honey singh".downcase
    if(line.match(junkremoveregexset))
      puts "note was found in line"
    else
      puts "No line was found"
    end

The output of this code is No line was found.

If I use this code then its working perfectly

junkremoveregex=[]
    regexes = JunkRemoveLineRegex.find(:all,:select => 'regex')

    regexes.each do |regex|
      junkremoveregex << regex.regex
    end

    puts junkremoveregex

    junktest=/note/

    junkremoveregexset=Regexp.union(junktest)
    line ="note thhat yo yo honey singh".downcase
    if(line.match(junkremoveregexset))
      puts "note was found in line"
    else
      puts "No line was found"
    end

Puts junkremoveregex gives /note/

How can this problem be solved ?

Upvotes: 1

Views: 85

Answers (3)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

As BroiSatse mentioned, your regex is coming in string format, you need to first convert it back to regex format. For that you need to use this gem http://rubygems.org/gems/to_regexp

"/note/".to_regexp
#=> /note/

or in your case

junkremoveregexset.to_regexp

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44685

If puts junkremoveregex prints /note/ it means that this is a string `"/note/". Do not treat those slashes as regex syntax - it is rather part of the regex itself, so your regex becomes:

/\/note\//

This obviously doesn't match anything. You need to modify your model not to include those slashes.

Apart from that Regexp.union does not convert strings into Regex so, you need to do it before you union your conditions. I would write your code like this:

junkremoveregex = JunkRemoveLineRegex.pluck(:regex).map {|string| Regexp.new string }

puts junkremoveregex

junktest=/note/

junkremoveregexset=Regexp.union(junkremoveregex)
line ="note thhat yo yo honey singh".downcase
if(line.match(junkremoveregexset))
  puts "note was found in line"
else
  puts "No line was found"
end

Upvotes: 0

Michael Durrant
Michael Durrant

Reputation: 96484

If they are stored as strings you may need to do:

>> Regexp.new junkremoveregex

Upvotes: 0

Related Questions