Question

am working for a client who wants to filter email addresses from a textfield, where every text is analyzed and email addresses replaced by something like #####$$$$.

I appreciate your assistance in advance.

Was it helpful?

Solution

You could find all email addresses in a text with a regex such as /\S*\@\S*/ (Test it on Rubular, might not be perfect) and then replace all matches with whatever you choose.

email_regex = /\S*\@\S*/
text = "This is test@example.com test string. Regex is regex@example.co.uk amazing."

result = text.gsub(email_regex, 'email_has_been_replaced')

p result
# => "This is email_has_been_replaced test string. Regex is email_has_been_replaced amazing."

In an ActiveRecord model:

class Post < AR::B
  EMAIL_REGEX = /\S*\@\S*/
  before_validation :remove_email_addresses_from_body

  private

  def remove_email_addresses_from_body
    self.body = body.gsub(EMAIL_REGEX, 'hidden_email')
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top