regexvb.net

.NET regex: add space before all & characters


How can I add a space before every & and - character if there aren’t spaces there already?

I've been looking on the internet to try and see how to retain the original character in the replacement value:

Private Function fPhraseSpacesLeadingAdd() As String

    Dim strClsPhrase As String = "Cobb& Co is nice. Also so is M& Sheer and B- Cafe."

    'Desired output: "Cobb & Co is nice. Also so is M & Sheer and B - Cafe."

    Dim strReturn As String = strClsPhrase

    Dim strItems = New String() {"&", "-"}

    For Each strItem As String In strItems
        Dim rg1 As New Regex("." + strItem)
        strReturn = rg1.Replace(strReturn, "\1 " + strItem)
    Next

    Return strReturn

End Function

PS: after that I would like to create separate functions for the following but hopefully I can figure those out using similar code:

Function fSpaceTrailingAdd()
'Follow : ; , & with a single space if none there

and

Function fSpaceTrailingRemove() 
'Remove any spaces after $ “ ‘ ( [ {

Solution

  • Are you requiring Regex?

    You can do it simply with String.Replace by removing any existing spaces and then adding the space to all.

    strRes = strInput.Replace(" &", "&").Replace("&"," &")
    

    Both & and - can be done with a single expression.

    strRes = strInput.Replace(" &", "&").Replace("&"," &").Replace(" -", "-").Replace("-"," -")
    

    Your additional functions can be accomplished the same way.

    With Regex you could handle the case of multiple spaces if that is required. With String.Replace you would need a loop. The * gets rid of multiple spaces in front.

    strRes = Regex.Replace(strInput, " *&", "&").Replace("&", " &")
    strRes = Regex.Replace(strRes, " *-", "-").Replace("-", " -")