2015-12-16 47 views
0

我正在嘗試編寫能讓我搜索通過表單提交的內容並查找內容中的電子郵件地址的代碼。下面是代碼和我收到的錯誤消息。搜索字符串以查找ruby中的電子郵件地址

Error: undefined method `match' for {"content"=>"this is a test [email protected]"}:ActionController::Parameters 

代碼:

class ChallengesController < ApplicationController 
    def create 
    @challenge = current_user.challenges.build(challenge_params) 
    challenge_params.match(/\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}\b/i) 
    # ... 
    end 

    private 

    def challenge_params 
    params.require(:challenge).permit(:content) 
    end 
end 
+0

什麼是你的問題? – sawa

+1

使用正則表達式來查找有效的電子郵件字符串是非常困難的,因爲[有效地址上有大量的變體](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate -an的電子郵件地址)。 –

回答

1

你是一個散列應用match

challenge_params是一個哈希值。該錯誤消息會,這個散列包含密鑰content這是你想要與match使用,因此重寫match行:

challenge_params["content"].match(/\b[A-Z0-9\._%+-][email protected][A-Z0-9\.-]+\.[A-Z]{2,4}\b/i) 
+1

此外,正則表達式不正確 - '.'必須在'[]'中轉義。 – BroiSatse

+0

沒有注意到。感謝將更新它在我的回答 – shivam

+3

@BroiSatse這是錯誤的。 Dot *不需要在方括號內轉義。 – mudasobwa

0

我是新來的寶石,所以我的答案可能是很「業餘-ish「,但有時最簡單的想法是最好的... 我會這樣做的方式是搜索@符號的索引。然後分析符號前後的每個字符,直到獲得空格並保存這些索引編號。使用這些索引號從字符串中提取電子郵件地址。

def email_address(str) 
at_index = str.index('@') 
temp = (at_index - 1) 
while str[temp] != ' ' 
    temp -= 1 
end 
begining_index = (temp + 1) 
temp = (at_index + 1) 
while str[temp] != ' ' 
    temp += 1 
end 
end_index = temp 
return str[begining_index..end_index] 

+1

這種方法的問題是,如果你得到如下字符串:'「一些隨機特殊字符1 @#$%!我的電子郵件:[email protected]」' – shivam

+0

儘管描述很好,但你需要顯示代碼。我們明白你對Ruby是新手,但是對於問題的解決方案几乎總是需要代碼。 –

+0

@TheTinMan:抱歉。我編輯了我的原始答案,包括示例代碼... – Margal

相關問題