0

I'm creating a new record in Company table based on the logic below:

if company.nil?
  Company.create!(name: User.get_company_name(self.email)), domain: User.get_domain(self.email))
end

I want to extract the name of the domain to place in the Company table. Ie. If I have [email protected], I want to use regular expressions to substitute in 'Nike' as the company name. Or, in the case of [email protected], I'd want the company name to be 'Ryandrake'.

I already have this method I am using to extract the domain, but haven't managed to edit it to extract the name:

def self.get_domain(email_address)
  email_address.gsub(/.+@([^.]+.+)/, '\1') // Returns 'nike.com' or 'ryandrake.com'
end

Any help with modifying the method above to just return 'Nike' or 'Ryandrake' would be super helpful!

3 Answers 3

1

You can do just email_address[/(?<=@)[^.]+/] to get the desired name.

def self.get_domain(email_address)
  email_address[/(?<=@)[^.]+/]
end

Example:

"[email protected]"[/(?<=@)[^.]+/]
 => "gmail"

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pavan! This is the simplest and most elegant solution I was after.
0

Use this regex to capture the letters between @ and . : (?<=@)(.*)(?=\.) and then replace with whole string.

DEMO

or

gsub(/.+(?<=@)(.*)(?=\.).+/, '\1')

DEMO

Comments

0

Put the capturing group only to capture the word chars present next to @. .+ inside the capturing group helps to capture also the .com part also.

email_address.gsub(/.+@([^.]+).+/, '\1')

or

email_address.gsub(/.+@([^.]+)\..+/, '\1')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.