skip to Main Content

How can I add a space before every & and - characters if there are not 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 $ “ ‘ ( [ {

2

Answers


  1. 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("-", " -")
    
    Login or Signup to reply.
  2. As a single Regex you might try:

    (?=(?<!s)[&-])
    

    and replacing with a single space: .

    See: regex101


    Explanation

    • (?= ... [&-]): Find all positions after which you find "&" or "-" …
      • (?<!s): and before which there is no space
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search