Search code examples
stringcoldfusionfindcoldfusion-9

ColdFusion - String Function - Find Data In Between 2 Locations


I'm trying to sort out some string work.

And I need to pull the String Data in betweeen "Det:" and "Evt:" So only need the XXXB04 returned. There is always a space after Det: and a space before Evt:.

<cfset string = "Add: This Bit Of Data Det: XXXB04 Evt: F2016999999"> 
<cfset rpos = findNoCase("Evt:", string)>
<cfset rpiece = (rpos ? left(string, rpos - 1) : string)>
<br>RPIECE???
<br>
<cfoutput>#rpiece#</cfoutput>
<br><br>
<cfset det = "#Listlast(rpiece,"Det:")#">
<cfset final = "#RTrim(det)#"> 
<cfoutput>#final#</cfoutput>

Trying to split it into 2 string checks... With the first stuff - I can get rid of the Evt: stuff - 2nd function doesn't get me exactly whats to the right of Det:


Solution

  • This code should work for your example:

    <cfset string = "Add: This Bit Of Data Det: XXXB04 Evt: F2016999999"> 
    
    <cfset startpos = findNoCase("Det:", string)>
    <cfset startpos = startpos + 4>
    <cfset endpos = findNoCase("Evt:", string)>
    <cfset data = mid(string,startpos,endpos-startpos)>
    
    <cfoutput>
        start: #startpos#<br>
        end: #endpos#<br>
        data: [#data#]<br>
        trimmed data: [#trim(data)#]<br>
    </cfoutput>
    

    You can run it here: http://trycf.com/gist/865418cb4964ee375619eb316398bd76/acf?theme=monokai

    Code explained:
    <cfset startpos = findNoCase("Det:", string)> will point to the beginning of "Det:"in your string.

    Add: This Bit Of Data Det: XXXB04 Evt: F2016999999
                          ^
    

    <cfset startpos = startpos + 4> I am adding four to startpos to move the position past the "Det:" in the string.

    Add: This Bit Of Data Det: XXXB04 Evt: F2016999999
                              ^
    

    <cfset endpos = findNoCase("Evt:", string)> will point to the beginning of "Evt:" in your string.

    Add: This Bit Of Data Det: XXXB04 Evt: F2016999999
                                      ^
    

    Now with our pointers set we just get the characters between those two points.
    <cfset data = mid(string,startpos,endpos-startpos)>

    Add: This Bit Of Data Det: XXXB04 Evt: F2016999999
                              ^^^^^^^^
    

    Notice that the spaces before and after are also included. Those can be removed by calling the trim() function like so #trim(data)#.