How do I do elixir Regex instead of public Regex?

I was going to secure and valid email in my code, then I searched in google and found the Regex , but I can’t use this, because the # or … has been used in it.

public Regex :


and my code which not works :

	def validate_email(params) do
		Regex.match?(~r/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/, "#{params}")

Please help me for converting it to elixir Regex. Thank you in advance for the sake of answering me.

Elixir sigils can use different delimiters. Since in your regex I didn’t see any <, > characters I used them as delimiters.

iex(15)> Regex.match?(~r<[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?>, "test")
iex(16)> Regex.match?(~r<[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?>, "")

Otherwise you have to escape the the / character with \


I hope that is what you are after.

1 Like

Is my way correct?

{:ok ,  reg } = Regex.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")




Except that Regex.match? has an arity of two

Regex.match?(reg, "my string") 

your solution seems OK. It generates a regexp with the escaped version.

Maybe more experienced people can enlighten us with best practices.

1 Like

You should be very careful about validating email addresses with regex. My favourite approach is to “validate” it on the client (browser or app), and, if that verification fails, show a small “warning” note that the email address might not be valid (just so that the user might notice a possible typo) but allow to use it anyway and actually check it via email verification.


YES, PLEASE. I have a simple gmail userid since I joined early. There are close to a dozen people who have mistakenly given my email address instead of theirs for various services. The services that send a verification email that I ignore are awesome! The ones that assume they gave the right address are a pain.