Delete consecutive spaces (1 Viewer)

Guus2005

AWF VIP
Local time
Today, 09:35
Joined
Jun 26, 2007
Messages
2,645
Looking for a way to delete consecutive spaces.
Preferably a one-liner

The replace command doesn't cut it.
Code:
?replace("Dim intI              as Integer","  "," ")
results in
Code:
Dim intI       as Integer

I was thinking of a regular expression but i need some help there.

Thanks.
 

Minty

AWF VIP
Local time
Today, 08:35
Joined
Jul 26, 2013
Messages
10,355
Add a space to the search string and remove the space from the replace - nearly gets you there;

Code:
?replace("Dim intI              as Integer","   ","")
Dim intI  as Integer
 

theDBguy

I’m here to help
Staff member
Local time
Today, 01:35
Joined
Oct 29, 2018
Messages
21,358
Hmm, a regular expression won't probably be a one-liner unless you put it in a function and call it in your one line code. Just thinking out loud...
 

Guus2005

AWF VIP
Local time
Today, 09:35
Joined
Jun 26, 2007
Messages
2,645
Problem is i don't know how many spaces are in the string. I don't want to loop the replace command until the length doesn't change anymore.

And i found that \s{2,} as a regular expression selects all consecutive spaces (2 or more).
Next step would be to replace it with a single space...

Keeping you posted.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 16:35
Joined
May 7, 2009
Messages
19,169
Code:
Public Function RegExpReplace(ByVal WhichString As String, _
        ByVal Pattern As String, _
        ByVal ReplaceWith As String, _
        Optional ByVal IsGlobal As Boolean = True, _
        Optional ByVal IsCaseSensitive As Boolean = True) As String
    With CreateObject("vbscript.regexp")
        .Global = IsGlobal
        .Pattern = Pattern
        .IgnoreCase = Not IsCaseSensitive
        RegExpReplace = .Replace(WhichString, ReplaceWith)
    End With
End Function

expr = RegExpReplace(expr, "[\ ]{2,}", " ")
 

sxschech

Registered User.
Local time
Today, 01:35
Joined
Mar 2, 2010
Messages
791
Sorry. reread post and mentions not to loop. Leaving in case of use to someone else, or let me know and I'll delete.

Non regex vba:
Code:
Function RemoveEXTRASpaces(SpaceyWord As String) As String
'http://www.vbforums.com/showthread.php?609658-REmoving-multiple-spaces-from-a-string
'Remove extra spaces
'20151112
    Do While InStr(1, SpaceyWord, "  ")
        SpaceyWord = Replace(SpaceyWord, "  ", " ")
    Loop
    
    'Do While True
    '    Mlen1 = Len(SpaceyWord)
    '    SpaceyWord = Replace(SpaceyWord, " ", " ") '2 spaces replaced with 1
    '    Mlen2 = Len(SpaceyWord)
    '    If Mlen2 = Mlen1 Then
    '        Exit Do
    '    End If
    'Loop
    RemoveEXTRASpaces = SpaceyWord
End Function


Code:
? removeextraspaces("Dim intI              as Integer")
Dim intI as Integer
 
Last edited:

Users who are viewing this thread

Top Bottom