我想找到一種方法讓我從一個字符串(從數據庫中取出)動態創建一個正則表達式對象,然後用它來過濾另一個字符串。這個例子是從git提交消息中提取數據,但理論上任何有效的正則表達式都可以作爲字符串出現在數據庫中。Ruby中的動態正則表達式
會發生什麼
>> string = "[ALERT] Project: Revision ...123456 committed by Me <[email protected]>\n on 2009- 07-28 21:21:47\n\n Fixed typo\n"
>> r = Regexp.new("[A-Za-z]+: Revision ...[\w]+ committed by [A-Za-z\s]+")
>> string[r]
=> nil
我希望發生
>> string = "[ALERT] Project: Revision ...123456 committed by Me <[email protected]>\n on 2009- 07-28 21:21:47\n\n Fixed typo\n"
>> string[/[A-Za-z]+: Revision ...[\w]+ committed by [A-Za-z\s]+/]
=> "Project: Revision 123456 committed by Me"
完美,感謝 - 我知道我必須做一些微妙的錯誤。 – davidsmalley 2009-08-01 08:13:57