Skip to main content
July 27, 2009
Question

How to manipulate strings using Regular Expressions?

  • July 27, 2009
  • 4 replies
  • 1308 views

Hi,

I have a piece of code where I need to remove all blank spaces, slashes ("/" and "\"), etc with an underscore ("_").

I'm currently doing it in 2 lines:

<!--- Remove blank spaces --->

<cfset columnName = replaceNoCase(trim(arguments.queryObject[item])," ","_","All")>

<!--- Remove slash --->
<cfset columnName = replaceNoCase(trim(columnName),"/","_","All")>

Is there a much simpler way to do the above in 1 line?

Thanks and regards,

Yogesh Mahadnac

This topic has been closed for replies.

4 replies

Dileep_NR
Inspiring
July 28, 2009

try this

<cfset resourcename="tets\sdgg  fjsjd/">
<cfoutput>#ReReplace(resourcename,"[\\ /]","_","ALL")#</cfoutput>

Participating Frequently
July 27, 2009

I agree with TLC-IT that in many cases regular expressions can be more trouble than they're worth, but in this particular instance the expression needed is simple enough that it would simplify the code a bit - especially down the road if you run across other characters that need to be replaced.  The code would look something like this: <cfset string = reReplaceNoCase(trim(arguments.queryObject[item]),"[\s\\/]","_","all") />

Inspiring
July 27, 2009

Oh yes, I agree entirely.  If uttering the word, "regular expression" does not produce and reactions  in your "shop," they are positively the cat's meow for string-munching tasks exactly like this one.  If your co-workers can instantly understand and grok what you have written, then this is an incredibly powerful feature of the language, and ideal for this very application.  I'm just cautioning that "regular-expressions can become 'write-only.'  If they produce blank looks, stick to whatever is abundantly clear."  Or, leave a good book on Regular Expression Syntax sitting strategically close to the vending-machine.

Inspiring
July 27, 2009

Sure!  You can "name that tune" in just one line...  but is it worth the effort?  I mean, "one line vs. two?"

(He continued, quietly putting on his Perl hat... neatly embroidered  "TMTOWTDI")

If you do want to do it, even as just an exercise in frustration , then regular-expressions are the right tool to use.  REReplaceNoCase() is, indeed, the function you want.  A regular-expression can be written which matches, as you say, "blank spaces, slashes ("/" and "\"), etc."  Then you use the function to replace "all" occurrences with an underscore.

Now, having said that ... "never mind what is 'efficient.'  What is abundantly clear?"  The regular expression would indeed be "clear enough," but the difference between "one" and "a few" lines-of-code might be, literally, not worth the time.  Your call.

Inspiring
July 27, 2009

REReplaceNoCase()