Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Useful functions collection


  • Please log in to reply
5 replies to this topic
ObiWanKenobi
  • Members
  • 83 posts
  • Last active: Oct 17 2015 05:37 PM
  • Joined: 21 Aug 2012

Hello, I opened a thread about small functions that could be quite useful in your daily working routines:

 

I will begin with RegExSplit:

 

With RegExSplit function you can split a String by a regular expressin pattern and you will receive an array as a result:

RegExSplit(ByRef psText, psRegExPattern, piStartPos:=1)
{
	aRet := []
	if (psText != "")
	{
		iStartPos := piStartPos
		while (iPos := RegExMatch(psText, "P)" . psRegExPattern, match, iStartPos))
		{
			sFound := ExtractSE(psText, iStartPos, iPos-1)
			aRet.Push(sFound)
			iStartPos := iPos + match
		}
        sFound := ExtractSE(psText, iStartPos)
        aRet.Push(sFound)
	}
	return aRet
}

ExtractSE(ByRef psText, piPosStart, piPosEnd:="")
{
	if (psText != "")
	{
		piPosEnd := piPosEnd != "" ? piPosEnd : StrLen(psText)
		return SubStr(psText, piPosStart, piPosEnd-(piPosStart-1))
	}
}

Parameters for RegExSplit:

psText                      the text you want to split

psRegExPattern      the Regular Expression you want to use for splitting

piStartPos               start at this posiiton in psText (optional parameter)

 

function ExtractSE() is a helper-function to extract a string at a specific start and end position.

 

Example:

aResult := RegExSplit("Hello, world, hey", "\s*\,\s*")

 

will yield the following result:

aResult[1] := "Hello"

aResult[2] := "world"

aResult[3] := "hey"

 

Another example for splitting variable sText by (multiple) new lines:

aResult := RegExSplit(sText, "(\r?\n)+")



ObiWanKenobi
  • Members
  • 83 posts
  • Last active: Oct 17 2015 05:37 PM
  • Joined: 21 Aug 2012

Extracting parts of an array:

 

- ArrayExtractSE(ByRef paArray, piStart, piEnd:="")

1st paramerter: Array you want to extract part from

2nd parameter: start position

3rd parameter: end position (optional, if omiited it will automatically be array length)

 

- ArrayExtractL(ByRef paArray, piStart, piLen:="")

1st paramerter: Array you want to extract part from

2nd parameter: start position

3rd parameter: length of extraction (optional, if omiited it will automatically be array length)

ArrayExtractSE(ByRef paArray, piStart, piEnd:="")
{
    aRet := []
    
    iArrayLength := paArray.Length()
    
    if (iArrayLength == 0)
        return aRet
    
    if (piStart < 1)
        piStart := 1
    else if (piStart > iArrayLength)
        piStart := iArrayLength
    
    if (piEnd == "" || piEnd == 0 || piEnd > iArrayLength)
        piEnd := iArrayLength
    else if (piEnd < 1)
        piEnd := 1
    
    iDiff := (piEnd + 1) - piStart
    
    if (iDiff > 0)
    {
        Loop, % iDiff
        {
            aRet.Push(paArray[piStart + (A_Index - 1)])
        }
    }
    
    return aRet
}

ArrayExtractL(ByRef paArray, piStart, piLen:="")
{
    aRet := []

    iArrayLength := paArray.Length()
    
    if (iArrayLength == 0)
        return aRet
    
    if (piStart < 1)
        piStart := 1
    else if (piStart > iArrayLength)
        piStart := iArrayLength
    
    if (piLen=="" || piLen==0)
    {
        iEnd := iArrayLength
    }
    else
    {
        iEnd := piStart + (piLen - 1)
        if (iEnd > iArrayLength)
            iEnd := iArrayLength
        else if (iEnd < 1)
            iEnd := 1
    }
    
    iDiff := (iEnd + 1) - piStart
    
    if (iDiff > 0)
    {
        Loop, % iDiff
        {
            aRet.Push(paArray[piStart + (A_Index - 1)])
        }
    }
    
    return aRet
}


ObiWanKenobi
  • Members
  • 83 posts
  • Last active: Oct 17 2015 05:37 PM
  • Joined: 21 Aug 2012

RecursiveBracketParser with deepness level count

 

Parameters:

psText: text with nested brackets

paBracket: array with brackets e.g. ["(", ")"]

piStartPos: position to start from (1=default)

_piLevel: internal level count

 

Code + example:

RecursiveBracketParser(ByRef psText, paBracket, piStartPos:=1, _piLevel:=0)
{
    iPos := piStartPos
    while (iPos <= StrLen(psText))
    {
        if (SubStr(psText, iPos, StrLen(paBracket[1]))==paBracket[1])
        {
            iPos := RecursiveBracketParser(psText, paBracket, iPos+1, _piLevel+1)
        }
        else if (SubStr(psText, iPos, StrLen(paBracket[2]))==paBracket[2])
        {
            ; do replacement
            sReplacement := "[*MYREPLACEMENT*]"
            psText:=ReplaceSE(psText, piStartPos-1, (iPos-1)+StrLen(paBracket[2]), sReplacement)
            iDiff:=iPos+StrLen(paBracket[2])-piStartPos

            ; calculate difference between old found string and replacement for iPos reset
            iPos+=(StrLen(sReplacement)-iDiff)
            
            ; test output
            o := "Level: " . _piLevel . "`nProcessed Text:`n" . psText
            MsgBox, % o
            return iPos++
        }
        else
            iPos++
    }
}

ReplaceSE(ByRef psText, piPosStart, piPosEnd:="", ByRef psReplacement:="")
{
    if (psText!="")
    {
        piPosEnd := piPosEnd != "" ? piPosEnd : StrLen(psText)
        sBefore := SubStr(psText, 1, piPosStart-1)
        sAfter := SubStr(psText, piPosEnd+1, StrLen(psText))
        return sBefore . psReplacement . sAfter
    }
    else
    {
        return psReplacement
    }    
}

sText=
(
    (a (1)b (2 (3) (4)) c (5))
)

RecursiveBracketParser(sText, ["(", ")"])

Alternative with RegEx and no deepness level counting:

Str =
(
a (1) b (2 (3) (4)) c (5) d
a (1) b (2 (3) (4)) c (5)
)
MsgBox % RegExReplace(Str, "`am)\(([^()]|(?R))*\)", "[*MYREPLACEMENT*]")


ObiWanKenobi
  • Members
  • 83 posts
  • Last active: Oct 17 2015 05:37 PM
  • Joined: 21 Aug 2012

Transfer selected text into a variable and paste a string very fast via clipboard:

 

ClipCopy(piMode:=0)

- with piMode 0 selected text is copied and with piMode 1 selected text is cut

 

ClipPaste(psText)

ClipCopy(piMode := 0)
{
    clpBackup := ClipboardAll

    Clipboard=

    if (piMode == 1)
        sCopyKey := "vk58sc02D" ; Cut
    else
        sCopyKey := "vk43sc02E" ; Copy

    SendInput, {Shift Down}{Shift Up}{Ctrl Down}{%sCopyKey% Down}
    ClipWait, 0.25
    SendInput, {%sCopyKey% Up}{Ctrl Up}

    sRet := Clipboard

    Clipboard := clpBackup

    return sRet
}

ClipPaste(ByRef psText)
{
    if (psText != "")
    {
        clpBackup := ClipboardAll

        sPasteKey := "vk56sc02F" ; Paste

        Clipboard := psText

        SendInput, {Shift Down}{Shift Up}{Ctrl Down}{%sPasteKey% Down}

        ; wait for clipboard is ready
        iStartTime := A_TickCount
        Sleep, % 100
        while (DllCall("GetOpenClipboardWindow") && (A_TickCount-iStartTime<1400)) ; timeout = 1400ms
            Sleep, % 100
        
        SendInput, {%sPasteKey% Up}{Ctrl Up}

        Clipboard := clpBackup
    }
}

Example:

sText =
(join`r`n
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et
ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est
Lorem ipsum dolor sit amet.
)

F11::
sSelectedText := ClipCopy()
MsgBox, % sSelectedText
return

F12::
ClipPaste(sText)
return


ObiWanKenobi
  • Members
  • 83 posts
  • Last active: Oct 17 2015 05:37 PM
  • Joined: 21 Aug 2012

PadNum(piNum, piCharCount) - adds zeros before integer

 

piNum: your number

piCharCount: total count of numbers to generate for output, with "0" as pad-prefix

PadNum(piNum, piCharCount)
{
	; http://msdn.microsoft.com/en-us/library/windows/desktop/ms647550
	; Calls the API's wsprintf() to pad the number
	VarSetCapacity(sRet, 20)  ; Ensure the variable is large enough to accept the new string.
	DllCall("wsprintf", "Str", sRet, "Str", "%0" . piCharCount . "d", "Int", piNum, "Cdecl")  ; Requires the Cdecl calling convention.
	return sRet
}

; Example
MsgBox % PadNum(55, 4)


ObiWanKenobi
  • Members
  • 83 posts
  • Last active: Oct 17 2015 05:37 PM
  • Joined: 21 Aug 2012

Functions StringStartsWith, StringEndsWith return true if a string starts or ends with a string.

 

Parameters:

psText: your Text you want check

psSearch: beginning/ending string

StringStartsWith(ByRef psText, ByRef psSearch)
{
    if (psText != "" && psSearch != "") {
        iSearchLen := StrLen(psSearch)
        if (SubStr(psText, 1, iSearchLen) == psSearch)
            return true
    }
    return false
}

StringEndsWith(ByRef psText, ByRef psSearch)
{
    if (psText != "" && psSearch != "") {
        iTextLen := StrLen(psText)
        iSearchLen := StrLen(psSearch)
        if (SubStr(psText, iTextLen + 1 - iSearchLen, iSearchLen) == psSearch)
            return true
    }
    return false
}