Jump to content

is this the best way to replace string from array ?


Recommended Posts

Happy new year

is this the best way to replace string from array ?
 

#include <array.au3>

Local $change[0]
_ArrayAdd($change, "is|test|good|it")

$text = "this %0 a %1 , and %3 works %2"
ConsoleWrite($text & @CRLF)

For $i = 0 To UBound($change) -1
    $text = StringReplace($text,'%' & $i,$change[$i])
Next

ConsoleWrite($text & @CRLF)
Edited by Spider001
Link to comment
Share on other sites

another way :

#include <array.au3>

Local $change[0]
_ArrayAdd($change, "is|test|good|it")


$text = "this %0 a %1, and %3 works %2"

$text = Execute (  StringRegExpReplace('"' & StringReplace( $text , '"', '""') & '"', "%(\d+)", """ & Execute('\$change[$1]') & """)  )

ConsoleWrite($text & @CRLF)

Edit :

Also, if you store each word in string variable, you can use AutoItSetOption("ExpandVarStrings", 1), like this :

AutoItSetOption("ExpandVarStrings", 1)
$var0 = "is"
$var1 = "test"
$var2 = "good"
$var3 = "it"

$text = "this $var0$ a $var1$ , and $var3$ works $var2$"
ConsoleWrite($text)

Maybe it's possible to do the same thing with an array (I don't know how...)

Edited by jguinch
Link to comment
Share on other sites

I wouldn't say this example is a better way to replace a string from an array, just another way.

$aChange = StringSplit("is|test|well|it", "|", 2)

Local $text = "This %0 a %1, and %3 works %2."
ConsoleWrite("Original: " & $text & @CRLF)

Local $sTextChanged = Execute('"' & StringRegExpReplace($text, "%(\d+)", """ & $aChange[$1] & """) & '"')
ConsoleWrite("Changed:  " & $sTextChanged & @LF)

#cs Returns:-
Original: This %0 a %1, and %3 works %2.
Changed:  This is a test, and it works well.
#ce
Link to comment
Share on other sites

  • Moderators

Malkey, your example really explains how the Execute() function works... Neat :) .

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

I don't know why I used Execute twice in my example... o:)

BTW, you must double the quotes to allow quotes in the original string, otherwise the replacement will fail :

Local $change[4] = ["is", "test", "good", "it"]
Local $text = "this %0 a ""%1"", and %3 works %2"

ConsoleWrite ( Execute (  StringRegExpReplace('"' & $text & '"', "%(\d+)", """ & $change[$1] & """)  ) & @CRLF)

; Doubling the quotes
ConsoleWrite ( Execute (  StringRegExpReplace('"' & StringReplace( $text , '"', '""') & '"', "%(\d+)", """ & $change[$1] & """)  ) & @CRLF)
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...