Reguläre Ausdrücke lesbarer gestalten

Im Blog von PHP in Action hat sich – dagfin – seine Gedanken gemacht wie man Reguläre-Ausdrücke etwas _lesbarer_ gestalten kann.
Hier ein Auszug seines Artikels:
….
….Anyway, when I use regular expressions (regexes), I often feel the need to make them more readable. I do all sorts of things to achieve that. Commenting them is a pretty basic way.
The x modifier allows you to insert comments into the regex itself. All whitespace is ignored, and so is text after # at the end of a line:
$regex =
'/(w+s+){6} # Word followed by spaces, repeated six times
w+ # Last word
/x';
I always thought this was wonderful, but today I finally realized it's completely unnecessary. Using concatenation to split the regex costs us a few more characters, but it's more flexible, since we can split it anywhere we want:
$regex =
'/(w+s+)'. // Word followed by spaces
'{6}'. // Repeated six times
'w+'. // Last word
'/ '.
In ordinary program code, it's often useful to extract well-named methods instead of using comments. So naturally I think this way with regexes as well. It's possible to name the parts of the expression. The plainest way, just to show the principle, is using variables for example:
$word = "w+";
$spaces = "s+";
$regex = "/($word$spaces){6}$word/";
….
….(To be continued, I think…)
Ich bin dann mal auf die fortsetzung gespannt
Den ganzen Beitrag findet Ihr im PHP in Action Blog