Name : rSubstitute Author : JasonGrossman? Revision : IoWiki? 0.87
// Regular expression substitutions, with wild cards. Jason.Grossman@staff.usyd.edu.au
// usage example: "wombats are cuddly" rSubstitute ("([a-z][ao][a-z])([a-z][ao][a-z])", "\\2-\\1") // ==> "bat-woms are cuddly"
regexCache := Map clone Buffer rSubstitute := method (findRegex, substituteRegex,
r := regexCache atIfAbsentPut (findRegex, Regex clone setPattern (findRegex)) // cache compiled regular expressions, for speed
r setString (self asString)
regexMap := Map clone
maxSubstitutionTerms := (substituteRegex length / 3 + 1 roundUp) // a safe upper bound on the number of substitution terms, each of which takes 3 chars to specify ("\\1" etc.)
r allMatches foreach (i, v,
if (v type != "List") then (v := list (v))
for (n, maxSubstitutionTerms, 0,
groupN := v at (n)
regexMap atPut ("\\" .. n asString, groupN or "")
)
self := self replace (v at (0), substituteRegex replaceMap (regexMap))
)
self
)
