Skip to main content
June 3, 2011
Answered

Insert space in a string

  • June 3, 2011
  • 1 reply
  • 1615 views

I need to insert space after each eight character in a string.
Eg:

<cfset mytoken ="ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD">

<cfoutput>
<cfset replaceChar = ' '>
<cfset mytoken =Insert(replaceChar, mytoken, 8)>
<cfset mytoken =Insert(replaceChar, mytoken, 17)>
<cfset mytoken =Insert(replaceChar, mytoken, 26)>
<cfset mytoken =Insert(replaceChar, mytoken, 35)>
<cfset mytoken =Insert(replaceChar, mytoken, 44)>
<cfset mytoken =Insert(replaceChar, mytoken, 53)>
<cfset mytoken =Insert(replaceChar, mytoken, 62)>
mytoken:#mytoken#<br />


The above gives me result as
mytoken:ABCDEFGH IJKLMNOP QRSTUVWX YZABCDEF GHIJKLMN OPQRSTUV WXYZABCD


Can I achieve the same result using regular expresssion and reduce the code?

    This topic has been closed for replies.
    Correct answer Owainnorth

    Thanks both of you.

    If the string contains alphanumeric values,
    <cfset mytoken ="ABC33FG5666JKLMNOPQRSTUVWXYZABCDEFG666KLMNOPQRSTUVW555ABCD">
    then
    I tried to change it as
    reReplaceNoCase(mytoken, "([a-z][0-9]{1,8})", "\1 ", 'all')

    But it doesn't yield the correct result.
    The first set must be 'ABC33FG5'. But the above regular expression gave it as 'ABC33 FG5'.



    Not quite, but nearly. This:

    reReplaceNoCase(mytoken, "([a-z][0-9]{1,8})", "\1 ", 'all')

    Means "a letter, followed by one to eight numbers". You need:

    reReplaceNoCase(mytoken, "([a-z|0-9]{1,8})", "\1 ", 'all')

    Which means "one to eight letters or numbers". As Adam pointed out earlier, you can simplify it further:

    reReplaceNoCase(mytoken, "([a-z|0-9]{8})", "\1 ", 'all')

    1 reply

    Owainnorth
    Inspiring
    June 3, 2011

    Hell yeah you can!

    Give this a bash:

    reReplaceNoCase("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "([A-Z]{1,8})", "\1 ", 'all')

    Inspiring
    June 3, 2011

    You'd just want {8} rather than {1,8} in there, wouldn't ya?

    --

    Adam

    Owainnorth
    Inspiring
    June 3, 2011

    I did think that, but didn't know whether (although it worked) doing so would be technically valid for the remaining two characters at the end.

    Thinking about it more in this case you don't want a space at the end anyway so yes, the {8} would do the job. I think I was considering the case that you wanted the last two as a group, who knows. Maybe I was drunk at the time.

    As Adam points out - you can trim it down even more. A little more svelte than your original code I'd say