css

Sunday, January 29, 2012

How to replace last occurrence of substring in coldfusion

I get a lot of questions lately on how to extract a substring from a string. Below you can find 4 examples on how to extract a specific substring from a string. It is not to difficult if you know how to write regular expressions. If you have no experience with regex writting these rules can give you a major headache.
<!--- Replace the last occurence of test in the string --->
<cfset example_string = "test abc test 123 test def test 456">
<cfoutput>
#rereplace(example_string,'(.*)(test )(.*)','\1\3','one')#
</cfoutput>
<!--- Output: test abc test 123 test def 456 --->
Below some other examples of how to replace a specific substring from a string.

Replace second occurrence of substring in a string
<!--- Replace the second occurence of test in the string --->
<cfset example_string = "test abc test 123 test def test 456">
<cfoutput>
#rereplace(example_string,'(.*?)(test )(.*?)(test )(.*)','\1\2\3\5','one')#
</cfoutput>
<!--- Output: test abc 123 test def test 456 --->
Replace the first occurrence of substring in a string
<!--- Replace the second occurence of test in the string --->
<cfset example_string = "test abc test 123 test def test 456">
<cfoutput>
#rereplace(example_string,'(.*?)(test )(.*)','\1\3','one')#
</cfoutput>
<!--- Output: abc test 123 test def test 456 --->
Replace the penultimate occurrence of substring in a string
<!--- Replace the penultimate occurence of test in the string --->
<cfset example_string = "test abc test 123 test def test 456">
<cfoutput>
#rereplace(example_string,'(.*)(test )(.*?)(test )(.*)','\1\3\4\5','one')#
</cfoutput>
<!--- Output: test abc test 123 def test 456 --->

1 comment:

Giancarlo Gomez said...

Nice! Thanks for this tip!