问题
Trying to use a before_save in my Post model and then regex to replace anything that looks like an email with the word 'forbidden'. This is to cut down on spam from comments/posts created by users in a discussion board.
It is currently giving me a syntax error; but I am sure it is more than that? How do I fix it?
Post.rb
before_save :remove_emails
# Prevents and replaces any emails or URLs posted by user as <forbidden>
def remove_emails
self.post = post.gsub^(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$, "forbidden")
end
回答1:
According to doc,
- There is no
gsub^function. you have to usegsuborgsub! - Pattern (first parameter) should be surrounded by '/' (slash)
回答2:
remove the ^ right after gsub.
回答3:
With some adaptations on the Regexp posted in this question, you can try :
# Prevents and replaces any emails or URLs posted by user as <forbidden>
def remove_emails
self.post.gsub!(/(http|https):\/\/[a-z0-9-\.]+([\-\.]{1}[a-z0-9-\.]+)*[a-z]{2,5}\S*/i, 'forbidden')
end
来源:https://stackoverflow.com/questions/9098591/removing-email-address-using-regex-and-before-save