Question

There is a variable being set as follows (through custom tag invocation)

<cfset str = Trim( THISTAG.GeneratedContent ) />

The contents of THISTAG.GeneratedContent looks like

FNAME|MNAME|LNAME Test|Test|Test

The code I am having trouble understanding is as follows:

<cfset str = str.ReplaceAll(
            "(?m)^[\t ]+|[\t ]+$",
            ""
            ) />

<cfset arrRows = str.Split( "[\r\n]+" ) />

The above line of code should generate array with contents as

arrRows[1] = FNAME|MNAME|LNAME
arrRows[2] = Test|Test|Test

But on dumping the array shows following output:

FNAME|MNAME|LNAME Test|Test|Test

I do not understand what both regular expressions are trying to achieve.

Was it helpful?

Solution

This one...

<cfset str = str.ReplaceAll(
    "(?m)^[\t ]+|[\t ]+$",
    ""
    ) />

..is removing any tabs/spaces that are at the beginning or end of lines. The (?m) turns on multiline mode which causes ^ to match "start of line" (as opposed to its usual "start of content"), and similarly $ means "end of line" (rather than "end of content") in this mode.

This one...

<cfset arrRows = str.Split( "[\r\n]+" ) />

...is converting lines to an array, by splitting on any combination of consecutive carriage returns and/or newline characters.


Bonus Info

You can actually combine these two regexes into a single one, like so:

<cfset arrRows = str.split( '\s*\n\s*' ) />

The \s will match any whitespace character - i.e. [\r\n\t ] and thus this combines the removal of spaces and tabs with turning it into an array.
(Note that since it works by looking for newlines, the trim on GeneratedContent is necessary for any preceeding/trailing whitespace to be removed.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top