views:

345

answers:

5

What is the quickest way in ColdFusion (or Java) for converting a string as such:

Input:
79827349837493827498

Output:
\79\82\73\49\83\74\93\82\74\98

I'm taking an ldap guid and escaping it for a query.

I can do it as a series of MID reductions like this:

  <CFSET V1 = "">
  <CFSET RetVal = "">
  <CFLOOP CONDITION="#V1# NEQ''">
      <CFSET RetVal = RetVal & "\" & MID(V1,1,2)>
      <CFSET V1 = MID(V1,3,2000)>
  </CFLOOP>

But it seems like there would be something more elegant, like a regular expression replace.

+11  A: 

I haven't tested this, so the syntax might be off, but you should be able to do something like:

<cfset V1 = REReplace(V1,"([0-9]{2})","\\\1","all")>
Eli
thanks. Exactly what I was looking for. I just realized my examples didn't have characters in it, but LDAP Guid does. So the Regex ought to be closer to (\w{2}).
Tom Hubbard
A: 

how about...

<cfset input = "79827349837493827490">
<cfset output = "">

<cfloop from="1" to="#len(input)#" index="count" step="2">
   <cfset output &= "\" & mid(input, count, 2)>
</cfloop>
Henry
+2  A: 

In Java you could do

String text = text.replaceAll("(..)","\\\1");
Peter Lawrey
Which is exactly what you could do in ColdFusion as well. But I believe it is: .replaceAll("(..)","\\$1") - Java back references work with a dollar sign.
Tomalak
A: 

I don't know ColdFusion, but here's a simple Java approach:

private String injectBackslashes(String string) {
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < string.length() / 2; ++i)
     sb.append('\\').append(string.substring(2*i, 2*i+2));
    return sb.toString();
}
Carl Manaster
+1  A: 

Here is another possible way.

<cfset input = "79827349837493827498"/>
<cfset output = input/>

<cfloop from="#len(output)-2#" to="0" index="i" step="-2">
    <cfset output = insert("\",output,i)/>
</cfloop>

<cfoutput>#output#</cfoutput>
Jayson
cool, I thought insert() wouldn't work, but looping down works! nice!
Henry
oh... 'to' should be 1, right?
Henry
No, 'to' should be 0 because an insert() function position parameter of 0 prefixes the string.
Jayson