coldfusion Working with RegExp Replace callbacks


If you want more than a simple string replacement with common regular expressions you certainly run into trouble and hit the wall when discovering the limits of the regex functions Coldfusion has. There is no build-in function like php's preg_replace_callback.


reThe regular expression
strThe string which should be applyed the the regex
callbackThe function where the captured grouped will be passed in if a match was found. There the matches can be processed


Because Coldfusion itself does not offer what we want, we make recourse to the variety of Java, which is — as we all know — on top of Coldfusion. Java offers us java.util.regex.Pattern.

So here is what we actually do:

  1. Invoke the Compile method from the Pattern Class object and passing the regex pattern to it (which probably deposits the regex pattern for later use).
  2. Invoke the Matcher method on what the Compile method returned and passing the string where the pattern should be executed.
  3. Test if matching was successfull by invoking the find method on what the Matcher method returned.

If matcher.find() returns true, we could say "That's it", but there is one little thing we have to consider: Java's Pattern object stores the groups and gives us access via another function, which is not always the best way for further processing and not that consistent regarding how other programming languages handle this case. Therefore we loop over so that we can pass an array containing the captured groups to the callback function. And now we can say: "That's it!"