Jump to content

_ExpandVarStrings!


MrCreatoR
 Share

Recommended Posts

Hi all,

Here is a custom function to expand the strings/macros - it can expand even variables with one $ symbol, i.e - "Some $Var"

And also, this function bypassing the bug(?) i found recently :) ...

$Var = "Our Value"
$Str = "Our String"

;================= Example with $iMode = -1, default - Only $String$ expanded =================
$sString = "This is <$Var$> and this is <$Str$>"
$ExpandedStr = _ExpandVarStrings($sString, -1)

MsgBox(64, "Expand Var Strings", "Was:" & @LF & $sString & @LF & @LF & "Expanded:" & @LF & $ExpandedStr)
;==========================================================================================================


;================= Example with $iMode = 1, Only $String expanded =================
$sString = "$Var goes here, and $Str goes here"
$ExpandedStr = _ExpandVarStrings($sString, 1)

MsgBox(64, "Expand Var Strings", "Was:" & @LF & $sString & @LF & @LF & "Expanded:" & @LF & $ExpandedStr)
;==========================================================================================================


;================= Example with $iMode = 2, All strings expanded ($String and $String$) =================
$sString = "$Var not equel $Str$"
$ExpandedStr = _ExpandVarStrings($sString, 2)

MsgBox(64, "Expand Var Strings", "Was:" & @LF & $sString & @LF & @LF & "Expanded:" & @LF & $ExpandedStr)
;==========================================================================================================


;===============================================================================
; Function Name:    _ExpandVarStrings()
; Description:      Expand string variable/macro inside string (using different modes).
; Parameter(s):        $sString - String that contain variables that need to be expanded.
;                      $iMode - Define the expand mode...
;                               -1 - (default) will expand only $Var$/@Macro@.
;                               1 - will expand only $Var/@Macro.
;                               2 - will expand $Var$/@Macro@ and $Var/@Macro.
; Requirement(s):   None.
; Return Value(s):  On success - Return initial string with expanded variables.
;
;                   On failure - If $sString not contain string variables that need to be expanded (according to $iMode), 
;                                will returned initial $sString.
;
; Note(s):          Only Global Scope variables are expanded.
; Author(s):        G.Sandler (a.k.a CreatoR)
;===============================================================================
Func _ExpandVarStrings($sString, $iMode=-1)
    Local $aExtractStrs, $sPattern, $sEval, $Old_Opt_EVS
    Local $sRetStr = $sString, $sExpndStr = ""
    Local $aSymbExpnd[2] = ["$", "@"]
    
    Local $Old_Func_Opt_EVS = Opt("ExpandVarStrings", 0)
    
    For $i = 0 To 1
        Switch $iMode
            Case 1
                $sPattern = "(?i)(\" & $aSymbExpnd[$i] & "[0-9a-z_]+)"
            Case 2
                $sPattern = "(?i)(\" & $aSymbExpnd[$i] & "[0-9a-z_]+\" & $aSymbExpnd[$i] & ")|(\" & $aSymbExpnd[$i] & "[0-9a-z_]+)"
            Case Else
                $sPattern = "(?i)(\" & $aSymbExpnd[$i] & "[0-9a-z_]+\" & $aSymbExpnd[$i] & ")"
        EndSwitch
        
        Local $aExtractStrs = StringRegExp($sString, $sPattern, 3)
        If Not IsArray($aExtractStrs) Then ContinueLoop
        
        For $iE = 0 To UBound($aExtractStrs)-1
            If $i = 0 Then
                $sEval = Eval(StringReplace($aExtractStrs[$iE], $aSymbExpnd[$i], ""))
                If $sEval <> "" Then $sRetStr = StringReplace($sRetStr, $aExtractStrs[$iE], $sEval)
            ElseIf $iMode <> -1 Or StringRight($aExtractStrs[$iE], 1) = $aSymbExpnd[$i] Then
                $sExpndStr = $aExtractStrs[$iE]
                If StringRight($sExpndStr, 1) <> $aSymbExpnd[$i] Then $sExpndStr &= $aSymbExpnd[$i]
                $Old_Opt_EVS = Opt("ExpandVarStrings", 1)
                $sExpndStr = $sExpndStr
                Opt("ExpandVarStrings", $Old_Opt_EVS)
                If $aExtractStrs[$iE] <> "" Then $sRetStr = StringReplace($sRetStr, $aExtractStrs[$iE], $sExpndStr)
            EndIf
        Next
    Next
    
    Opt("ExpandVarStrings", $Old_Func_Opt_EVS)
    Return $sRetStr
EndFunc

Edit 1: Fixed small problem when Opt("ExpandVarStrings", 1) was previously set by user.

Edit 2: Added note to the func comment about the usage limitation of this function.

Edited by MsCreatoR

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Maybe i don't get it right, but why not let execute do all the work?

Func _Expand($s)
   Local $o = Opt("ExpandVarStrings",1)
   $s = StringReplace($s,'"','""')
   Local $r = Execute('"' & $s & '"')
   Opt("ExpandVarStrings",$o)
   Return $r
EndFunc

$a = "aa"
$x = "xx"
ConsoleWrite(_Expand("@AutoItVersion@, $a$, $x$") & @CRLF)

Please don't get me wrong, i don't want to criticize your code...

CoProc Multi Process Helper libraryTrashBin.nfshost.com store your AutoIt related files here!AutoIt User Map
Link to comment
Share on other sites

why not let execute do all the work?

Well, this will not work then:

$a = "aa"
$x = "xx"
ConsoleWrite(_Expand("3.2.8.1, $a, $x") & @CRLF)oÝ÷ ٩ݺ¹

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Btw, there is no need to use Execute in that case..

Func _Expand($s)
    Local $o = Opt("ExpandVarStrings",1)
    $s = $s
    Opt("ExpandVarStrings",$o)
    Return $s
EndFunc

$a = "aa"
$x = "xx"
ConsoleWrite(_Expand("@AutoItVersion@, $a$, $x$") & @CRLF)

:)

Or i am not fully understand of what you mean by this example :">

Edited by MsCreatoR

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Ok it was just a rhetorical question, no need to answer, i read your patterns.

I know now what functionality your after :)

But anyway, this will never work:

Func whatever()
   $x = "some val"
   ConsoleWrite(_ExpandVarStrings("$x$") & @CRLF)
EndFunc
whatever()

Because $x is not in the global scope, thus Eval() cant reach it.

Same goes for my suggested concept...

CoProc Multi Process Helper libraryTrashBin.nfshost.com store your AutoIt related files here!AutoIt User Map
Link to comment
Share on other sites

But anyway, this will never work:

Too bad :) - i thoght that Eval() can handle all kind of variables.

I added note to the comments of the function, because i can not see a solution for that one.

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

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...