coldfusion Working with RegExp Replace callbacks

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

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.

Parameters

ParameterDetails
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

Remarks

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 matcher.group() so that we can pass an array containing the captured groups to the callback function. And now we can say: "That's it!"



Got any coldfusion Question?