Click to search Andy Jarrett.co.uk RSS feed

Loading Twitter

Using RegEx to cut down on code

I sometimes forget how useful/powerful RegEx can be. Take the following bit of CFIF logic

[sourcecode language="plain"] <cfset username = trim(form.uname) /> <cfif len(username) LT 4> <cfset errorMsg = "Your username is too short" /> <cfelseif NOT reFindNoCase("[\w]", username, 1, "false")> <cfset errorMsg = "Your username is too short" /> </cfif> [/sourcecode]

A quick regex guide: the "\w" reference stands for "word character", which translates to [A-Za-z0-9_] n.b.the underscore as well

You can actually add on to the regex and at the same time cut down a lot of the logic by doing the following:

[sourcecode language="plain" gutter="true" toolbar="true" wraplines="true"] <cfif NOT refindnocase("[\w]{4,}", username, 1, "false")> <cfset errorMsg = "Usernames must be 4 characters in length and contain [A-Za-z 0-9 _" /> </cfif> [/sourcecode]

The key is "{4,}". Using the curly braces to specify a specific amount of repetition of "word characters" and is equivilant to "len(username) LT 4"

Comments Comments (2) | Print Print | Send Send | 409 Views

(Comment Moderation is enabled. Your comment will not appear until approved.)
Pretty nifty!
Peach on our huge preference of handbags and purses

[url=http://handbags.getenjoyment.net]dior handbags replica[/url]
[url=http://handbagson.totalh.com]dolce gabbana handbags[/url]
[url=http://ladybags.fizwig.com]fake handbag[/url]
[url=http://mybags.zxq.net]fake handbag prada[/url]
[url=http://unbag.v3host.be]givenchy handbags[/url]
BlogCFC by Raymond Camden + Twitter @AndyJ + ColdFusion jobs + Contact Me + Snippets/Downloads + RSS .