XML technologies / Regular expressions / The art of writing regular expressions / Think!
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
I do not want to conclude The art of writing regular expressions without telling a story illustrating how a little thought can greatly improve an NFA regular expression. I once had a small problem in Emacs, which uses a traditional NFA. I wanted to find contractions such as “don’t”, “I’m” and “we’ll”, but not apostrophes before or after a word. I built a regex matching a word ˹(\<\w+)˼, followed by the Emacs equivalent of ˹'([tdm]|re|ll|ve)˼. That worked, but I then realized that ˹\<\w+˼ was more than necessary: \w alone sufficed. If an apostrophe is preceded by \w, it is certainly also preceded by \w+, and every word has a beginning (\<) anyway. I only cared where these contractions occurred; match length was irrelevant. With just \w, the regex was over ten times faster.
A little thought really can go a long way. I hope this chapter has given you some ideas to consider.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln
back to top