I have a specification at work that says my software needs to see a URL like this:

https://blog.rectorsquid.com/derf?test={id}&test2={data}

and then open the URL as if it were something like this:

https://blog.rectorsquid.com/derf?test=12345&test2=hellothere

I first wrote some code that would split the input using the open curly brace as a delimiter and then would split each member of the resulting array using the closing curly brace. Each array element in the second split would get stored into one larger array and the result was that every other entry in the array was one of these placeholders. Here’s the very ugly code:

You can see my code that processes each element of the array. I was not proud of this solution, to say the least, but it did only take me about five minutes to figure it out and another five minutes to write it and test it. Today, I decided to create an extension function for the String class that would take an expression and then call a handler block of code for each component of the string that matched the expression. This reduces the amount of code but certainly decreases performance a bit. Since the user in my app is tapping on a link to open it, a few extra milliseconds is unimportant – this code doesn’t get called thousands of times for each frame of a game, or anything critical like that.

Here is the extension function:

This is a nice compact function that could handle any sort of expression I need. In fact, I’m starting to wonder if there isn’t already a function like this that I could use for this purpose. Writing my own function was a good exercise for me so I dont have any regrets even if there already is something that does this.

Now the code to call this and replace the placeholders is quite compact and more self-explanatory:

I hope that I find another use for this new parsing function. I’m proud to have made something cleaner and prettier than just the first thing that came to mind.