HurleyShanabarger

Replace leading Whitespace

8 posts in this topic

Hey guys,

I need to replace the leading whitespace per string and have the following functions. Version 2 is slighty faster, but is there a way to perform the action with only one line of regular expression?

 

Func _StringReplaceLeadingWS_V1(Const ByRef $sString, Const $sReplace = "")
    Local $_lv_sWS = StringRegExpReplace($sString, "^( *)(.*)$", "\1")

    Return StringRegExpReplace($_lv_sWS, " ", $sReplace) & StringRegExpReplace($sString, "^( *)(.*)$", "\2")
EndFunc   ;==>_StringReplaceLeadingWS_V1


Func _StringReplaceLeadingWS_V2(Const ByRef $sString, Const $sReplace = "")
    Local $_lv_sWS = StringRegExpReplace($sString, "^( *)(.*)$", "\1")

    Return StringRegExpReplace($_lv_sWS, " ", $sReplace) & StringTrimLeft($sString, StringLen($_lv_sWS))
EndFunc   ;==>_StringReplaceLeadingWS_V2

Thanks in advance.

Share this post


Link to post
Share on other sites



Look at StringStripWs 

Share this post


Link to post
Share on other sites

I need to replace, not strip/remove the whitespace.

Share this post


Link to post
Share on other sites

Sorry misread your post

Share this post


Link to post
Share on other sites
8 minutes ago, Subz said:

Although in saying that

ConsoleWrite(StringReplaceWS('   some text', 'next ') & @CRLF)
Func StringReplaceWS($sString, $sReplace)
    Return $sReplace & StringStripWS($sString, 1)
EndFunc

 

Thank you, I had that one, but that one is only adding the replace string one time and not for each whitespace.

Share this post


Link to post
Share on other sites
1 hour ago, Malkey said:

This appears to work.

Local $Str = "  Here is a atring."

ConsoleWrite(_StringReplaceLeadingWS_V3($Str, "next ") & @CRLF)


Func _StringReplaceLeadingWS_V3($sString, $sReplace = "")
    Return StringReplace($sString, " ", $sReplace, (StringLen($sString) - StringLen(StringStripWS($sString, 1))))
EndFunc   ;==>_StringReplaceLeadingWS_V3

 

And it is way faster then the other solutions, thanks alot.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now