Regex to extract optional middle name

Hi

I have a subject line which i am using to extract first and last names of some users . sometimes it happens that there would be a middle name

I am able to successfully extract the first two and as the middle name is optional , how can i create a proper regex

sample subject :requesting the authorization for pxxx123 Fname Lname Mname- other details (Testing)
Regex used : (?<=[a-z]\d{3}\D{3}\s)(\S+)\s(\S+) : Successfully extracts first 2 strings after pxxx123(id) as they are always available.

Hi,

How about the following?

m = System.Text.RegularExpressions.Regex.Match(yourString,"[a-z]\D{3}\d{3}\s(?<FIRSTNAME>\S+)\s+(?<LASTNAME>\S+)\s+(?<MIDDLENAME>[^\s\-]+)?")

Then

m.Groups("FIRSTNAME").Value
m.Groups("LASTNAME").Value
m.Groups("MIDDLENAME").Value

If there is no middle name, m.Groups(“MIDDLENAME”).Value returns empty.

This expression assumes - character or white space follows name.

Sample20221122-2aL.zip (2.3 KB)

Regards,

Thank you , this works perfectly.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.