Reguläre Ausdrücke lesbarer gestalten

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








XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Blogroll

Lorem ipsum

These 3 boxes are widgets and can be edited through the admin page, just like the sidebar.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Impressum