0

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?

CodeMann
  • 157
  • 9
  • `@"\w+\s[a-zA-Z]&"` [Anchors](https://learn.microsoft.com/en-us/dotnet/standard/base-types/anchors-in-regular-expressions) – Alexander Petrov May 10 '19 at 21:33
  • Hello Anchors. Unfortunately, this particular Regex seems to ignore a "Single-Character" after the FirstName. I've tested it with both an initial and with a fully spelled out middle name and it completely ignores just an initial following the first name. Dropping the Ampersand, which is what I started with, at least allows my code to add a period after a MI. However, what I need is something that will instead ignore the fully spelled out middle name, but recognize a MI. – CodeMann May 11 '19 at 15:47
  • 1
    Sorry, I made a typo. There should be `@"\w+\s[a-zA-Z]$"`. Symbol `$` - end of the string. – Alexander Petrov May 11 '19 at 15:54
  • @Alexander, this is exactly what I was looking for. It successfully finds any single-letter following the first name, but ignores any fully spelled out middle names. Thanks – CodeMann May 11 '19 at 20:20

0 Answers0