# match_replace

Definition: | sequence res = match_replace(object needle, sequence haystack, object replacement, integer maxr=0)
Description: | Finds a "needle" in a "haystack", and replace any, or only the first few, occurrences with a replacement. needle: an object to search and perhaps replace. haystack: a sequence to be inspected. replacement: an object to substitute for instances of needle. maxr: number of items to replace, or 0 to replace all occurrences Returns a sequence, the modified haystack.
pwa/p2js: | Supported, though naturally I prefer to use substitute(), as per the examples below.
Comments: | Replacements will not be made recursively on the part of `haystack` that was already changed. If `maxr` is 0 or less, any occurrence of `needle` in `haystack` will be replaced by `replacement`. Otherwise, only the first `maxr` occurrences are replaced. If either `needle` or `replacement` are atoms they are treated as if you had passed in a length-1 sequence containing the said atom. This routine is defined in builtins\matchrepl.e (an autoinclude) and is provided only for compatibility with Euphoria.
Example: |
    ?match_replace("the","the cat ate the food under the table","THE")
    ?substitute("the cat ate the food under the table","the","THE")
    ?match_replace("the","the cat ate the food under the table","THE",2)
    ?substitute("the cat ate the food under the table","the","THE",2)
    ?match_replace('/',"/euphoria/demo/unix",`\`,2)
    ?substitute("/euphoria/demo/unix",'/',`\`,2)
    -- output (each twice):
    -- "THE cat ate THE food under THE table"
    -- "THE cat ate THE food under the table"
    -- `\euphoria\demo/unix`