Perl Regular Expressions

For everyone who did write a code someday comes the question of using regular expressions. Almost everybody has heart about automatic and regular languages. Assume you have all word for a given languages, which means all possible combination between the letters of a given alphabet. For all these possible word only few construct the “language” as we know this term. Of course there’s also need of grammatic, etc. But however we have the set of words in a given language.

Than comes the task to find those of the words of the language that match a given condition. In fact the regular expressions are a powerful tool to do this job.

Using PHP you can use preg_ functions, which will perform a perl regular expressions match. In my case I had to find in about 180 .html files specific words.

Assume the files contain something like:

<!-- wellformed html comment -->
<tr>
<td class="classname1"><img ...></td>

<td class="classname2">

<a ... >

Word to match

</a>

</td>

</tr>

<tr>

<td ...></td>

<td ...></td>

</tr>

<!--wellformed html comment-->

The regular expressions for preg_replace function I used was something like this:

'/^[t|s]*<tr>.*?$n^.*?<td.*?</td>.*?$n.*?
<td.*?$n.*?<a.*?>.*?$n.*?Word  to  match.*?$n.*?</a>.*$n.*?</td>.*$n.*?
</tr>.*$n.*?<tr.*$n.*?<td.*$n.*?<td.*$n.*?</tr>/m'

… and it worked for me. In fact if you use ‘s’ instead of ‘m’ modifier that’s gonna be you mistake cause of the multiple matches before the current tag you want to match.

2 thoughts on “Perl Regular Expressions

  1. For everybody who wants to use the power of the regular expressions in a file system (such as Linux), better go to man pages of ‘sed’ and ‘grep’ commands… 😉

  2. Good post. Your messages are really interesting. To have a good site you should not only to add something, but do it interesting. You do your best.

Comments are closed.