I have a lot of article drafts sitting unused in my WP DB and I’ve decided to release them even though I don’t have very much time to get into details.
Here’s one of them.
I always comment the code I write like:

// Bogdan -> initializing dispatcher
$this->dispatcher->init();
//-

Very often I’m required to extract the parts of the code I wrote, even though they are not full functions or classes, but just simple variables, or…

Here’s a general Regular Expressions rule to do just that:

(Bogdan)([^/]|/[^/]|//[^-])*(//-)

Here’s the logic behind it:
Step 1. Search for “Bogdan”. If found go to Step 2
Step 2. ([^/]|/[^/]|//[^-])* -> this means retrieve any character that is not “/”. If “/” is found, go to the next part of the “OR”, /[^/] which means you are allowed to pick “/” followd by any character except “/”. If that still doesn’t work, switch to the last part of the “OR”, //[^-] which means get anything except “//-”. If “//-” is found, the loop made by the second group exits and the regexp continues to the last group, which is in fact the end of what we are searching for “//-”.

The whole trick is in the second group. Suppose that instead of “//—–” your stop signal would have been “/* s”. The new regexp would look like:

(Bogdan)([^/]|/[^\*]|/\*[^ ]|/\* [^s])*(/\* s)

Be extra careful to add slashes before special chars (like “*”). Also be very very careful not to put extra spaces inside the Regular Expression. Every space gets interpreted, cause the space is a character, it’s not like in regular programming where you can intend your code with any number of spaces you want.

Save and share: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Mixx
  • Google
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Comments

2 Responses to “Cool trick to extract only what you need using regular expressions”

  1. Inspired2C on December 20th, 2009 10:18 pm

    “Be extra careful to add slashes before special chars (like “*”)”

    should be

    Be extra careful to add back slashes before special chars (like “*”)

  2. Inspired2C on December 20th, 2009 10:20 pm

    You should warn visitors that their email address will be posted with their Comments!

    For one, I do not appreciate it!

Leave a Reply




Advertisements