May
29
Cool trick to extract only what you need using regular expressions
Filed Under JavaScript, PHP, Programming
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.
Comments
Leave a Reply







