| Operator Type: | Function |
| Operator Scope of Action: | Item |
| Operator Purpose: | Data manipulation |
String/List.replace("pattern","replacement")
New to v5.7.0 this operator allows simple text transformations without use of runCommand as was hitherto required.
pattern and replacement are both one of:
- an action code expression (which includes just referencing a single attribute name')
- a quoted string; quoted strings may be either:
- a literal string (i.e. actual text)
- a regular expression
$MyString.replace("pattern","replacement")
In its simplest form, the operator creates a new string in which each occurrence of pattern is replaced by the string replacement, i.e. a global replacement. The source string is not changed by replace; if you wish to change the string itself, write back over the source attribute:
$MyString = $MyString.replace("Hello","Goodbye")
transforms a $MyString value of "Hello World" to "Goodbye World".
Where pattern is a regular expression, and may contain wildcard characters such as "." (which matches any character) or "*" (which matches 0 or more occurrences of the preceding character). Thus ".*" matches zero or more instances of any character.
Where parentheses in pattern create multiple back-references, replacement strings can include $1, $2, etc., to insert the relevant back-reference matched string ($1 through $9 allowed).
Examples:
$MyString.replace("Spenser","Spencer")
$MyString.replace("(a|e|i|o|u)","")// deletes all vowels
$MyString = "I do not like green eggs".replace("(green) (eggs)","$2 $1") "I do not like eggs green"
Although multiple matches can be replace with the same string, to replace multiple matches with different strings requires chained .replace() calls. Consider formatting a large number to Continental style. This means inserting spaces as the group delimiter and a comma for the decimal delimiter. assume $MyNumber is 1234567.89:
$MyString = $MyNumber.replace("(\d)(?=(?:\d{3})+([^\d]))","$1 ").replace("\.",",")
Now, 1234567.89 becomes "1 234 567,89".
