SaraDob SaraDob - 1 year ago 80
C# Question

Regex c#: Last Name in an email to include only one hyphen

I have a textbox, which takes firstname.Lastname for my organisation.
The last name may or may not include hyphen.If it includes, then it should appear,
1) Only once in last name
2) Not at the beginning of lastname
3) not at the end of last name

I have this Regex figured out


This includes "-" in last name. But will not satisfy above conditions.

Im still learning regex, and is taking time to figure out this.
Please help

-Thank you

Answer Source

You need to add one more nested group inside the last name part:


See the regex demo


  • ^ - start of string
  • (?!.{51}) - no more than 50 chars in the string requirement
  • [a-zA-Z]+ - 1+ ASCII letters
  • (?:\.[a-zA-Z]+(?:-[a-zA-Z]+)?)? - an optional sequence of:
    • \. - a dot
    • [a-zA-Z]+ - 1 or more ASCII letters
    • (?:-[a-zA-Z]+)? - an optional sequence of:
      • - - a hyphen
      • [a-zA-Z]+ - 1+ ASCII letters
  • $ - end of string.

To declare this pattern, use a verbatim string literal:

var pattern = @"^(?!.{51})[a-zA-Z]+(?:\.[a-zA-Z]+(?:-[a-zA-Z]+)?)?$";

To match any Unicode letters, use \p{L} instead of [a-zA-Z].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download