Language C#. In the 'Leave' event of a textbox, I'm using Regex to try to find a single Middle Initial following a FirstName and a Space. If a match is found, I then TitleCase the beginning character of the FirstName and MI and add a period "." after the middle initial. Otherwise, I just TitleCase the FirstName.
I show a section of my code below:
private void FirstName_Leave(object sender, EventArgs e)
{
//Regex looks for a single letter following first name, i.e.
//middle initial, and adds a '.' period after the letter.
Match match = Regex.Match(FirstName.Text, @"\w+\s[a-zA-Z]");
if (match.Success)
{
FirstName.Text = ReturnTitleCase(FirstName.Text + ".");
}
else
{
FirstName.Text = ReturnTitleCase(FirstName.Text);
}
}
This works fine when the end-user enters just a single character after the FirstName, i.e., Mike E. However, if the user enters a fully spelled out middle name such as Mike Edward, then a period is entered after the middle name like 'Mike Edward.'
I've also tried other Regex syntax such as the following, from a StackOverFlow site shown below.looking for one or more characters in the FirstName, then one or more Space characters, followed by just a Single word character. However, this again adds a period "." after a spelled out middle name.
regex middle name initial with or without it there
Match match = Regex.Match(FirstName.Text, @"\w+[a-zA-Z]\s+\w?[a-zA-Z]");
Could someone suggest a Regex syntax that would check for Only a single character after the FirstName, but would ignore anything longer than just a single character middle initial?