DEV Community

Discussion on: How do you feel about regex?

Collapse
 
billraymond profile image
Bill Raymond

I am what you might call an ocassional developer. As an author, I created an app that helps me convert my work to ePub format.

One of the requirements with ePub is that you output all your files to xHTML. However, the output from my word processing software (Microsoft Word) outputs to some very haphazardly developed HTML that is not xHTML compliant.

I found a whole bunch of libraries that allow me to manipulate the output to xHTML, but in fact they did not do many of the things required to pass basic specifications. Specifically, in xHTML, tags must be lowercase. All of the libraries I worked with at the time made broad assumptions about the HTML structure and worse, did not do the basic conversion from uppercase tags to lowercase tags.

After spending way too much time dealing with this, I paid a developer to figure out the problem. One day later, he delivered three lines of regex code that handled the uppercase to lowercase issue and two other problems I was dealing with. Nearly a month of work and me trying to understand how all these libraries work and sudenly I had working code. My books are thousands of pages long and broken up into dozens of files. The regex code worked great everytime.

Having not known about regex until that moment, I went about using it everywhere. I used it when my XML output was not correct. I used it to fix the file output where special characters should be renamed with escape codes and much more.

I am willing to bet that while my code technically works, all that regex is probably a bad idea. Also, regex is not easy to read, so you really have to document it well.

Overall, I really do not like the structure because of it being hard to read, but will say that without it, I probably would have just tossed my app into the trash bin had I spent two more weeks on something as simple as fixing uppercase and lowercase letters along with a few edge case issues.

The drive to complete my app drove me to use regex in areas I probably should not have used it. For example, I used regex to modify some XML files and since I did not really know XML that well, I simply gave up learning it. Instead, I used the XML output from a library and then modified the file with REGEX. Really, I should have sat down and learned XML a little more.

Regex feels like one of those things we all refer to as monolith applications. It seems like you can do anything and everything with it, but the complexities in how you write proper regex and then create test cases all feels very convoluted. At the same time, there is something very tantalizing about 1-3 lines of regex code that would otherwise require customizing libraries, creating a custom API, or doing something else to solve some basic problems.

I am curious, do we know if there are alternatives that are easier to understand and use?