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"

Posted: 17-Jul-2009

View: 974

Permalink: here

Comments

Pretty nifty!

#1 William from Lagos
18/Jul/09 12:40 PM

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]

#2 Neemebamy
01/Jan/10 7:31 AM