Jump to content

_StringRegExpReplaceCallBack implementation


amel27
 Share

Recommended Posts

This UDF write as probable solution of "Assigned Feature Request" (Ticket #588)

RobSaunders, Valik and MsCreatoR Thanks for discussion

$sString = "This is a Test, a _stringRegExpReplaceEx test"
$sRetVar = _StringRegExpReplaceEx($sString, "\b(\w)(\w*)")
$iRepCnt = @extended

If @error Then
    MsgBox(16, "ERROR", "Err: "& @error &@CRLF& "Ext: "& @extended)
Else
    MsgBox(64, "Results of ", StringFormat("Initial String:\n%s\n\nReturn String:\n%s\n\nSubstrings found: %s", $sString, $sRetVar, $iRepCnt))
EndIf


; =============================================================================
; _StringRegExpReplaceEx($sString, $sPattern [,$sFunction])
; -----------------------------------------------------------------------------
; Replace text in a string based on regular expressions to text,
; returned by custom CallBack function
;
; $sString     : The string to check
; $sPattern    : The regular expression to compare.
; $sFunction   : Callback Function Name
;
; Return Value : Final String
;
; @Error         Meaning
; 0              Check @Extended for the number of replacements performed.
; 2              Pattern invalid. @Extended = offset of error in pattern.
; =============================================================================
Func _StringRegExpReplaceEx($sString, $sPattern, $sFunction = "_StringRegExpReplaceCallBack")
    Local Const $aBlank[10] = ['','','','','','','','','','']
    Local $aM1, $aM2, $sStrip, $aStrip, $aGroups, $sResult = ""

    $sStrip = StringRegExpReplace($sString, $sPattern, Chr(0))
    If @error Then Return SetError(@error, @extended, $sString)
    $aStrip = StringSplit($sStrip, Chr(0))

    $aM1 = StringRegExp($sString, $sPattern, 4)
    If IsArray($aM1) Then
        For $i=0 To UBound($aM1)-1
            $aGroups = $aBlank
            $aM2=$aM1[$i]
            For $j=0 To UBound($aM2)-1
                $aGroups[$j]=$aM2[$j]
            Next
            $sResult &= $aStrip[$i+1]
            $sResult &= Call($sFunction, $aGroups)
        Next
    EndIf

    $sResult &= $aStrip[$aStrip[0]]
    Return SetError(0, UBound($aM1), $sResult)
EndFunc ;==> _StringRegExpReplaceEx

; =============================================================================
; _StringRegExpReplaceCallBack ($aGroups)
; -----------------------------------------------------------------------------
; Custom user function for building replacement string
; base on found string and substrings (capture groups)
;
; $aGroups     : Array of searched substrings
;
;              : $aGroups[0] equal to "\0"
;              : $aGroups[1] equal to "\1"
;              : ...
;
; Return Value : Replacement string
; =============================================================================
Func _StringRegExpReplaceCallBack($aGroups)
    Switch $aGroups[1]
        Case "_"
            Return "_" & StringUpper(StringLeft($aGroups[2], 1)) & StringTrimLeft($aGroups[2], 1)
        Case "t", "T"
            Return StringUpper($aGroups[0])
        Case Else
            Return $aGroups[0]
    EndSwitch
EndFunc ;==> _StringRegExpReplaceCallBack
Link to comment
Share on other sites

I saw this as a feature request..

Haven't thoroughly tested it, but thanks for sharing.

If you follow the User Defined Functions Standards, and ensure there's no bugs this may be included with AutoIt. :P

Edited by mrRevoked
Don't bother, It's inside your monitor!------GUISetOnEvent should behave more like HotKeySet()
Link to comment
Share on other sites

  • 9 months later...

This UDF write as probable solution of "Assigned Feature Request" (Ticket #588)

RobSaunders, Valik and MsCreatoR Thanks for discussion

$sString = "This is a Test, a _stringRegExpReplaceEx test"
$sRetVar = _StringRegExpReplaceEx($sString, "\b(\w)(\w*)")
$iRepCnt = @extended

If @error Then
    MsgBox(16, "ERROR", "Err: "& @error &@CRLF& "Ext: "& @extended)
Else
    MsgBox(64, "Results of ", StringFormat("Initial String:\n%s\n\nReturn String:\n%s\n\nSubstrings found: %s", $sString, $sRetVar, $iRepCnt))
EndIf


; =============================================================================
; _StringRegExpReplaceEx($sString, $sPattern [,$sFunction])
; -----------------------------------------------------------------------------
; Replace text in a string based on regular expressions to text,
; returned by custom CallBack function
;
; $sString     : The string to check
; $sPattern    : The regular expression to compare.
; $sFunction   : Callback Function Name
;
; Return Value : Final String
;
; @Error         Meaning
; 0              Check @Extended for the number of replacements performed.
; 2              Pattern invalid. @Extended = offset of error in pattern.
; =============================================================================
Func _StringRegExpReplaceEx($sString, $sPattern, $sFunction = "_StringRegExpReplaceCallBack")
    Local Const $aBlank[10] = ['','','','','','','','','','']
    Local $aM1, $aM2, $sStrip, $aStrip, $aGroups, $sResult = ""

    $sStrip = StringRegExpReplace($sString, $sPattern, Chr(0))
    If @error Then Return SetError(@error, @extended, $sString)
    $aStrip = StringSplit($sStrip, Chr(0))

    $aM1 = StringRegExp($sString, $sPattern, 4)
    If IsArray($aM1) Then
        For $i=0 To UBound($aM1)-1
            $aGroups = $aBlank
            $aM2=$aM1[$i]
            For $j=0 To UBound($aM2)-1
                $aGroups[$j]=$aM2[$j]
            Next
            $sResult &= $aStrip[$i+1]
            $sResult &= Call($sFunction, $aGroups)
        Next
    EndIf

    $sResult &= $aStrip[$aStrip[0]]
    Return SetError(0, UBound($aM1), $sResult)
EndFunc ;==> _StringRegExpReplaceEx

; =============================================================================
; _StringRegExpReplaceCallBack ($aGroups)
; -----------------------------------------------------------------------------
; Custom user function for building replacement string
; base on found string and substrings (capture groups)
;
; $aGroups     : Array of searched substrings
;
;              : $aGroups[0] equal to "\0"
;              : $aGroups[1] equal to "\1"
;              : ...
;
; Return Value : Replacement string
; =============================================================================
Func _StringRegExpReplaceCallBack($aGroups)
    Switch $aGroups[1]
        Case "_"
            Return "_" & StringUpper(StringLeft($aGroups[2], 1)) & StringTrimLeft($aGroups[2], 1)
        Case "t", "T"
            Return StringUpper($aGroups[0])
        Case Else
            Return $aGroups[0]
    EndSwitch
EndFunc ;==> _StringRegExpReplaceCallBack

This example returns the same results as the script from post #1.

;
; Returns the same result as the example script,post #1, at
; http://www.autoitscript.com/forum/index.php?showtopic=82292&view=findpost&p=589332
Local $sString = "This is a Test, a _stringRegExpReplace test"

Local $sRetVar = StringRegExpReplace($sString, "\b(\w)(\w*)(, | |\z)", 'Call("_CallFunction","\1","\2","\3") & ')
Local $iRepCnt = @extended
;ConsoleWrite($sRetVar & @CRLF)

$sRetVar = Execute(StringTrimRight($sRetVar, 3))

MsgBox(64, "Results of ", StringFormat("Initial String:\n%s\n\nReturn String:\n%s\n\nSubstrings found: %s", _
        $sString, $sRetVar, $iRepCnt / 3)); 3 back-references used in regular expression replace parameter.


Func _CallFunction($a, $b, $c)
    If StringLen($b) > 1 And $a <> "_" Then
        $a = StringUpper($a)
        $b = StringUpper($b)
    EndIf
    Return $a & $b & $c
EndFunc   ;==>_CallFunction
;
Link to comment
Share on other sites

you don't need to use call when using execute

;
; Returns the same result as the example script,post #1, at
; http://www.autoitscript.com/forum/index.php?showtopic=82292&view=findpost&p=589332
Local $sString = "This is a Test, a _stringRegExpReplace test"

Local $sRetVar = StringRegExpReplace($sString, "\b(\w)(\w*)(, | |\z)", '_CallFunction("\1","\2","\3") & ');removed call because it's useless
Local $iRepCnt = @extended
;ConsoleWrite($sRetVar & @CRLF)

$sRetVar = Execute(StringTrimRight($sRetVar, 3))

MsgBox(64, "Results of ", StringFormat("Initial String:\n%s\n\nReturn String:\n%s\n\nSubstrings found: %s", _
        $sString, $sRetVar, $iRepCnt / 3)); 3 back-references used in regular expression replace parameter.


Func _CallFunction($a, $b, $c)
    If StringLen($b) > 1 And $a <> "_" Then
        $a = StringUpper($a)
        $b = StringUpper($b)
    EndIf
    Return $a & $b & $c
EndFunc   ;==>_CallFunction
;

Only two things are infinite, the universe and human stupidity, and i'm not sure about the former -Alber EinsteinPractice makes perfect! but nobody's perfect so why practice at all?http://forum.ambrozie.ro

Link to comment
Share on other sites

you don't need to use call when using execute

Xand3r

Thanks for the heads up. It is appreciated.

Malkey

Still intrigued by the possibilities, here is another example.

It creates a 2D array of all words per line.

;
; This example returns a 2D array. Rows are each line. The columns are each word in that line.
; StringRegExpReplace() returns each line into a StringRegExp() which returns an array as a parameter of the function, Test1.
; The RE pattern of StringRegExp can be modified to select specific data from each line to fill the array, not just each word.
#include <array.au3>

Global $aMain[3][7], $iRow = 0

Local $sStr = "Jack and Jill went up the hill." & @LF & _
        "The second line of the string $sStr" & @CRLF & _
        "And a third line of a string"

Execute(StringTrimRight(StringRegExpReplace($sStr, "(.*)(\v+|$)", 'Test1(StringRegExp("\1","\\b(\\w+)",3)) & '), 2))

_ArrayDisplay($aMain, "Results")

Func Test1($aArr)
    For $x = 0 To UBound($aArr) - 1
        $aMain[$iRow][$x] = $aArr[$x]
    Next
    $iRow += 1
    Return
EndFunc   ;==>Test1
;

I imagine, if/when this Feature Request is implemented, a script similar to this example would work without the use of the Execute command.

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