how to replace the last comma in a comma separated list with ' and '


I am using 2005 and I'm not very familiar with regular expressions.

If i had a comma separated list of items in a string, how would i locate the last comma in the list and replace it with ' and '

for example

me, you becomes me and you
me, you, barbara becomes me, you and barbara

thanks a lot
Who is Participating?
Robert SchuttConnect With a Mentor Software EngineerCommented:
Here's two options, with and without regex:
    Private Sub DoTests()
        Dim str1 As String = "me, you"
        Dim str2 As String = "me, you, barbara"

        MessageBox.Show(String.Format("'{0}' becomes '{1}'; '{2}' becomes '{3}'", str1, ReplaceLastComma(str1), str2, ReplaceLastComma(str2)))
        MessageBox.Show(String.Format("'{0}' becomes '{1}'; '{2}' becomes '{3}'", str1, ReplaceLastComma2(str1), str2, ReplaceLastComma2(str2)))
    End Sub

    Private Function ReplaceLastComma(ByVal s As String)
        Static re As New Regex("\s*,\s*([^,]*)$")
        Return re.Replace(s, " and $1")
    End Function

    Private Function ReplaceLastComma2(ByVal s As String)
        Dim p As Integer = InStrRev(s, ",")
        Return s.Substring(0, p - 1) & " and " & s.Substring(p + 1)
    End Function

Open in new window

Meir RivkinFull stack Software EngineerCommented:
        Dim str As String = "me, you, barbara"
        Dim index as integer = str.LastIndexOf(","c)
        str = str.Substring(0, index) & " and" & str.Substring(index + 1)

Open in new window

andiejeAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.