2014-10-08 29 views
2

我有一組正則表達式,我將它們存儲在數據庫的某個表中。我檢索它們並使用這些正則表達式應用某些操作,但它們不能按需要工作。Ruby on Rails:無法從數據庫檢索正則表達式

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 

該代碼的輸出是找不到行。

如果我用這個代碼,那麼它的工作完美

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 

提出junkremoveregex給人/ NOTE/

這又如何解決?

+0

請出示JunkRemoveLineRegex.find的'內容' – 2014-10-08 10:27:59

+0

由於(:選擇=>「正則表達式」:所有)我們需要看看你實際存儲的正則表達式的含義。 – 2014-10-08 10:29:02

+0

把junkremoveregex給/ note /。我想我已經指定了這個問題本身 – LearningBasics 2014-10-08 10:30:25

回答

1

由於提到BroiSatse,你的正則表達式是字符串格式來了,你首先需要將其轉換回正則表達式的格式。對於那些需要使用這個寶石http://rubygems.org/gems/to_regexp

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

或在您的情況

junkremoveregexset.to_regexp 
+1

它工作了!!只是檢查上面的解決方案,因爲它不需要任何依賴 – LearningBasics 2014-10-08 10:50:22

0

如果它們被存儲爲字符串,你可能需要做的:

>> Regexp.new junkremoveregex 
+0

junkremoveregex是一個數組,'Regexp.new'不接受它作爲參數。 – BroiSatse 2014-10-08 10:33:56

0

如果puts junkremoveregex打印/note/這意味着這是一個字符串`「/ NOTE /」。不要把這些作爲斜線正則表達式語法 - 這是相當的正則表達式本身的一部分,所以你的正則表達式變成:

/\/note\// 

這顯然不符合任何東西。 你需要修改你的模型不包括那些斜線。

除此之外,Regexp.union不會將字符串轉換爲正則表達式,因此您需要在合併條件之前執行此操作。我會寫你這樣的代碼:

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 
+0

NoMethodError:未定義的方法'pluck'for#。這個錯誤被拋出!其實我是鐵軌開發新手 – LearningBasics 2014-10-08 10:53:33

+0

@LearningBasics - 你使用哪個rails版本? – BroiSatse 2014-10-08 10:54:09

+0

rails版本是3.1.0 – LearningBasics 2014-10-08 10:56:41