SaraDob SaraDob - 1 month ago 4
C# Question

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

Friends,
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


^(?!.{51})[a-zA-Z]+(?:[.][a-zA-Z-]+)?$


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

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

^(?!.{51})[a-zA-Z]+(?:\.[a-zA-Z]+(?:-[a-zA-Z]+)?)?$
                                 ^^^^^^^^^^^^^^^ 

See the regex demo

Details:

  • ^ - 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].

Comments