Click here to Skip to main content
15,896,367 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm converting some old VB6 code to VB.NET and have it all up and running, except that one particular RegEx pattern isn't finding a match that it should be. Here's the code:
VB
' Check for last, first middle (Doe, John P.)
pattern = "[^ \f\n\r\t\v\,]+\,\s+\S+ "
If Regex.IsMatch(strName, pattern) Then
    subParseLastFirst(strName)
Else
    ' Check for first middle last (John P. Doe)
    pattern = "^\S+\s+\S+\s+\S+$"
    If Regex.IsMatch(strName, pattern) Then
        subParseFirstMiddleLast(strName)
    Else
        ' Check for first last (John Doe)
        pattern = "^\S+\s+\S+$"
        If Regex.IsMatch(strName, pattern) Then
            subParseFirstLast(strName)
        Else
            mblnHasError = True
            mstrErrorMessage = "Unable to parse."
        End If
    End If
End If
When I feed "Doe, John" into the code, it doesn't match on the first pattern, but it does match on the third, which treats the name as first, last. If I feed Doe, John P., the first test is a match. How should I code the pattern for Doe, John, and where should it appear in the nested if?
Posted

Try this:
' Check for last, first middle (Doe, John P.)
^[a-zA-Z]+,\s[a-zA-Z]+\s[a-zA-Z]+.$

' Check for first middle last (John P. Doe)
^[a-zA-Z]+\s[a-zA-Z]+.\s[a-zA-Z]+$

' Check for first last (John Doe)
^[a-zA-Z]+\s[a-zA-Z]+$


and add one more else if for last, first of "Doe, John"
^[a-zA-Z]+,\s[a-zA-Z]+$
 
Share this answer
 
v2
Dunno, maybe the \, ? Nuke it.

How about you try this one ^((?'last'\S+)(?'comma',))?\s*(?'first'\S+)\s*(?'middle'\S*?)(?(comma)|\s*(?'last'\S+))$ instead and access the Named Groups.
It still won't accept names that contain spaces (e.g. von Beethoven, Billy Ray X.), but it works for the examples:

Doe, John P.
Doe, John
John P. Doe
John Doe
 
Share this answer
 
v3
Deleted solution, changed to comment.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900