Jump to content

Replace leading Whitespace


Recommended Posts

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.

Link to comment
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.

Link to comment
Share on other sites

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

 

Edited by Malkey
Link to comment
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.

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...