The other day Nathan Strutz wrote a great post on finding and replacing text in your IDE (in my case I’m using Aptana/cfeclipse) using regular expressions.
This is more a reminder to me so that I try to use it (with the idea that it’ll become 2nd nature!), but I also had a play to see how I could use it in day to day coding. I’m sure others have more interesting uses, but here is where I can use it immediately:
Setting variables (using cfml rather than cfscript)
Often you have the need to set a large number of variables, I would actually use a <cfscript> block for this, but if I wanted to use <cfset> with the end result being something like:
I’ll need a reg exp, text to replace my matched content and initial code to search.
The reg exp
Note that I’m using 2 ‘groups’ separated by a space, this will be important when looking at the actual text to search on.
The ‘replace’ text to use
The initial source code which I’ll search on
Note that as have 2 ‘groups’ separated by a space, the end result would be
Nice
You can use (I believe) as many ‘groups’ as you want, here is an example which uses 3 for <cfparam>
The reg exp
The ‘replace’ text to use
The initial source code
The end result
As I said, I’m sure there are much better ways to achieve this as I suck at regular expressions. Anyone have any more uses?
One area I use it in a lot is when I have a large block of data, usually imported from Excel, that I need to turn into some CF code. (You could probably do this best using the spreadsheet as a datasource, but if you don’t want to setup a datasource every time you need some Excel data, this method works for me).
I just copy and paste from excel to Homesite+ , so the data looks like:
100 foo
101 bar
102 fubar
103 etc
Then I use regex like:
([0-9]+) ([[:print:]]+)
becomes
duncan
December 10th, 2007
hmmm, Wordpress strips html. try again:
One area I use it in a lot is when I have a large block of data, usually imported from Excel, that I need to turn into some CF code. (You could probably do this best using the spreadsheet as a datasource, but if you don’t want to setup a datasource every time you need some Excel data, this method works for me).
I just copy and paste from excel to Homesite+ , so the data looks like:
100 foo
101 bar
102 fubar
103 etc
Then I use regex like:
([0-9]+) ([[:print:]]+)
becomes
<cfset array[1] = “\1″>
<cfset array[2] = “\2″>
<cfset ArrayAppend(newarray, array)>
duncan
December 10th, 2007
ps, get the following error when I post comments:
WordPress database error: [Table 'chapter31.wp_post2cat' doesn't exist]
SELECT cat_ID AS ID, MAX(post_modified) AS last_mod FROM `wp_posts` p LEFT JOIN `wp_post2cat` pc ON p.ID = pc.post_id LEFT JOIN `wp_categories` c ON pc.category_id = c.cat_ID WHERE post_status = ‘publish’ GROUP BY cat_ID
duncan
December 10th, 2007
Ah thanks for that Duncan, I just upgraded Wordpress…seems my theme is out of date. I’ll have to take a peek.
Michael Sharman
December 10th, 2007