Brute-Force String Handling
This situation reminds me of a coding problem that came up recently. My pal, Brian Randell, was trying to quickly rip out some code that could retrieve a URL from an Internet Explorer favorite (*.FAV) file. These files contain information about your selected favorites, and contain data in old-fashioned INI format, like this:
Although the contents of this file aren't generally documented, Brian wanted to retrieve just the URL from the file, using Visual Basic .NET. He was in a rush, and asked if I had code lying about to parse INI files.
I had written a set of classes to handle this issue for VBA applications, but hadn't really ever had a need to handle the INI file format in managed code. I'm sure a quick search online would have turned up a similar set of managed classes, but since his only goal was to retrieve a value given a specified key, I figured that I could rip out some brute-force string handling code quicker than searching online.
shows the first pass at solving this string parsing problem. This code does its job by converting both the INI text (which Brian had already managed to load, using the System.IO namespace) and the key value to be located into upper case, and then using the IndexOf method to find the location of the string:
Dim startPos As Integer = _
If the sought item was found, the code attempts to find the end of the text line containing the item, searching for a CR/LF or the end of the text:
If startPos > 0 Then
Dim textLine As String
Dim endPos As Integer = iniText.IndexOf( _
ControlChars.CrLf, startPos + 1)
If endPos > 0 Then
textLine = iniText.Substring( _
startPos, endPos - startPos)
textLine = iniText.Substring(startPos)
' code removed here.
Finally, the code splits the found line at the "=", and trims the results to remove extra spaces:
Dim items() As String = _
If items.Length > 1 Then
returnValue = items(1).Trim()
Although this solution isn't elegant, it was quick to write and returned the required value. But it bothered me. As I was in the shower one morning, I was struck. "Isn't this a perfect scenario in which to use regular expressions?" I asked myself. Armed with the urge to make working code more elegant, I started again. This time, I did a quick bit of research into regular expressions in the System.Text.RegularExpression namespace. This feature provides a meta language that makes it possible for developers to craft incredibly rich search and replace operations based on complex write-only (that's my thought, anywayyou try reading one of these and figuring out what its purpose is) text expressions.