Function Reference


StringRegExpReplace

Replace text in a string based on regular expressions.

StringRegExpReplace ( "test", "pattern", "replace" [, count = 0] )

Parameters

test The string to check
pattern The regular expression to compare. See StringRegExp for pattern definition characters.
replace The text to replace the regular expression matching text with. To insert matched group text, \0 - \9 (or $0 - $9) can be used as back-references. (See remarks)
count [optional] The number of times to execute the replacement in the string. The default is 0. Use 0 for global replacement.

Return Value

Success: an updated string based on regular expressions. Check @extended for the number of replacements performed.
Failure: sets the @error flag to non-zero.
@error: 2 = Pattern invalid. @extended = offset of error in pattern.

Remarks

To separate back-reference replacements from actual (replaced) numbers, wrap them with curly braces, i.e: "${1}5".
If a "\" needs to be in the replaced string it must be doubled. This is a consequence of the back-references mechanism.
The "\" and "$" replacement formats are the only valid back-references formats supported.

See also the Regular Expression tutorial, in which you can run a script to test your regular expression(s).

Related

StringRegExp(), StringReplace()

Example

#include <MsgBoxConstants.au3>

Test1()
Test2()
Test3()

; This example demonstrates a basic replacement.  It replaces the vowels aeiou
; with the @ character.
Func Test1()
    Local $sInput = "Where have all the flowers gone, long time passing?"
    Local $sOutput = StringRegExpReplace($sInput, "[aeiou]", "@")
    Display($sInput, $sOutput)
EndFunc   ;==>Test1

; The following example demonstrates using back-references to change the date
; from MM/DD/YYYY to DD.MM.YYYY
Func Test2()
    Local $sInput = 'some text1 12/31/2009 01:02:03 some text2' & @CRLF & _
            'some text3 02/28/2009 11:22:33 some text4'
    Local $sOutput = StringRegExpReplace($sInput, '(\d{2})/(\d{2})/(\d{4})', ' $2.$1.$3 ')
    Display($sInput, $sOutput)
EndFunc   ;==>Test2

; The following example demonstrates the need to double backslash
Func Test3()
    Local $sInput = '%CommonProgramFiles%\Microsoft Shared\'
    Local $sOutput = StringRegExpReplace($sInput, '%([^%]*?)%', 'C:\\WINDOWS\\Some Other Folder$')
    Display($sInput, $sOutput)
EndFunc   ;==>Test3

Func Display($sInput, $sOutput)
    ; Format the output.
    Local $sMsg = StringFormat("Input:\t%s\n\nOutput:\t%s", $sInput, $sOutput)
    MsgBox($MB_SYSTEMMODAL, "Results", $sMsg)
EndFunc   ;==>Display