Home > Software design >  C# Regex for custom email and domain
C# Regex for custom email and domain

Time:09-16

I have a razor view with an input that uses this pattern:

pattern="^[a-zA-Z0-9._ -] &#64mydomain.com"
      

It works great using as a front-end validation. However, how could I transform it to a Regex if I want to check on the back-end of things as well?
My emails are constructed as follow:
"[email protected]"
I have tried this:

Regex regex = new Regex("\\^\\[a-zA-Z0-9\\._\\ -]\\ &#64mydomain\\.com", RegexOptions.IgnoreCase); 

However, this does not work as I expect since the condition is always false. Is there another way of getting this pattern to work with Regex?

Thanks in advance!

CodePudding user response:

Direct translation of your regex to C# .NET regex will look like

Regex regex = new Regex(@"^[A-Z0-9._ -] @mydomain\.com$", RegexOptions.IgnoreCase); 

Note there is no problem with @ chars handling in .NET regexps, so @ can be coded as @.

Details:

  • ^ - start of string
  • [A-Z0-9._ -] - one or more ( ) occurrences of any ASCII letter (A-Z, it is case insensitive due to the regex option used), digits (0-9), ., _, and -
  • @mydomain\.com - @mydomain.com string
  • $ - end of string.
  • Related