2011-05-29 19 views
1

我on Rails的3使用Ruby和我想显示的网址和电子邮件地址作为一个视图链接。我在表单输入文本字段中检索用户键入的URL和电子邮件地址信息,因此我需要使用正则表达式...自动检测在一个字符串值类型,以考虑到一个URL,电子邮件地址,

我该怎么办?


BTW

here我有以下正则表达式:

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])) 

当我尝试说出班里上述正则表达式我有一个麻烦,因为有一个reg_url申报错误:

class User < ActiveRecord::Base 

    def check 
    reg_url = (?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])) 
    ... 
    end 

end 

也许,要解决这个问题,我必须在底部插入一些其他字符(例如'\','/',...)...

+1

正如仅供参考,如果你没有使用Rails,你可以使用的URI ['URI :: extract'(http://rubydoc.info/stdlib/uri/1.9.2/URI#extract-class_method )方法标识的URL,然后在它们之间迭代和'gsub'的链接。 – 2011-05-30 00:14:10

+0

在Ruby中,用于写入一个正则表达式的正确语法是:'的regexp =/[0-9] /'或'的regexp = Regexp.new( '[0-9]')'。 – 2011-05-30 00:25:53

回答

4

如果我理解正确,那么在字符串你希望把所有的链接和电子邮件地址为锚标记?

如果是这样,那么你应该尝试的auto_link方法。

用法:

auto_link("Go to http://www.rubyonrails.org and say hello to [email protected]") 
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and 
#  say hello to <a href=\"mailto:[email protected]\">[email protected]</a>" 

您可能需要如果HTML出现在输出逃过auto_link调用之前包含关键字“原始”。

相关问题