Question

I'm trying to achieve what looks like not too complicated task with no results so far.

Here's a sample string:

<cfset myString = "cm: first_part; fn: second_part; There was a farmer who had a dog">

The required output should be:

"cm: <span class='highlight'>first_part</span>; fn: <span class='highlight'>second_part</span>; There was a farmer who had a dog"

How one would go about it? The notes/restrictions is that it has to be done in ColdFusion 10 (I would suspect using Regex).

So far what I've got so far is this:

<cfoutput>#ReReplace(myString,"(cm:)?:(.*?);","<span class='highlight'>"&REMatch("(cm:)?:(.*?);",myString)[1]&"</span>","one")#</cfoutput>

This of course only changes the first part between cm and the following ';'

Thanks!

Was it helpful?

Solution

Conditional on the answer to my questions above, replacing ^(cm: )(.*)(; fn: )(.*)(; .*?)$ with \1<span class='highlight'>\2</span>\3<span class='highlight'>\4</span>\5 might work.

This will not handle semicolons in second_part correctly.

OTHER TIPS

You can do both parts with a single expression like this:

rereplace
    ( myString
    , "(cm: |fn: )([^;]*)(?=;)"
    , "\1<span class='highlight'>\2</span>"
    , "all"
    )


It can be slightly simplified by using Java's replaceAll method, where lookbehind can be used to avoid the need for capturing groups:

myString.replaceAll
    ( "(?<=cm: |fn: )[^;]*(?=;)"
    , "<span class='highlight'>$0</span>"
    )


Whether matching individually like this is better than matching as part of the entire text (as per Adam's answer) will depend on the use case - i.e. how representative the sample string is to the real inputs, and what is expected to occur if there happens to be multiple cm/fn sections.

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