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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Robert SchuttSoftware 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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.