regular expression to match firstname.lastname or just firstname with length limit
I need a regex to use in .net that will match a user name as firstname or firstname.lastname with a maxlength of 50 characters. The firstname case is easy but with firstname.lastname I can't figure out how to only allow 50 minus len(firstname.) in the lastname.
^([开发者_Python百科a-zA-Z]{1,50})|([a-zA-Z]+[.][a-zA-Z]+)$
will match the firstname case but the second case of firstname.lastname will allow infinite characters in the firstname and lastname.
Easily done. Here is a C# snippet with a commented regex:
if (Regex.IsMatch(userNameString,
@"# Match username with max length of 50 chars
^ # Anchor to start of string.
(?!.{51}) # Assert length is 50 or less.
[A-Za-z]+ # First name.
(?: # Optional second name.
\. # Required dot separator.
[A-Za-z]+ # Last name.
)? # Last name is optional.
$ # Anchor to end of string.
",
RegexOptions.IgnorePatternWhitespace)) {
// Valid username
} else {
// Invalid username
}
^(?i)(?=(?:[a-z]\.?){1,50}$)[a-z]+(?:\.[a-z]+)?$
Will only match if number of [a-z]
s is between 1 and 50.
If the total length can never be more than 50, you can use this instead:
^(?i)(?=.{1,50}$)[a-z]+(?:\.[a-z]+)?$
This would do it.
^(?:([a-zA-Z]{1,50})|(?=.{1,51}$)[a-zA-Z]+[.][a-zA-Z]+)$
Essentially, I added a lookaround saying match (without capturing) 1-51 chars and then the end of line. I used 51 because I'm assuming that the .
should count in the length calculation.
Using a two-step validation would be so much easier and I don't see a reason to avoid it.
精彩评论