View comments | RSS feed

Using subexpressions

Parentheses group parts of regular expressions together into grouped subexpressions that you can treat as a single unit. For example, the regular expression "ha" specifies to match a single occurrence of the string. The regular expression "(ha)+" matches one or more instances of "ha".

In the following example, you use the regular expression "B(ha)+" to match the letter "B" followed by one or more occurrences of the string "ha":

<cfset IndexOfOccurrence=REFind("B(ha)+", "hahaBhahahaha")>
<!--- The value of IndexOfOccurrence is 5 --->

You can use the special character | in a subexpression to create a logical "OR". You can use the following regular expression to search for the word "jelly" or "jellies":

<cfset IndexOfOccurrence=REFind("jell(y|ies)", "I like peanut butter and jelly">
<!--- The value of IndexOfOccurrence is 26--->

ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | KnowledgeBase | Bug Reporting

Version 7

Comments


yacoubean said on Oct 11, 2005 at 11:50 AM :
I recently learned a trick that is awesome with subexpressions. You can use \x to get the contents of all of the subexpressions in your regular expression. For example with this:
(grape|peanut butter)( jell)(y|ies)
you can get these:
= 'grape' or 'peanut butter'
= ' jell'
= 'y' or 'ies'
This allows you to do this:
reReplace("grape jelly","(grape)( jell)(y|ie)"," jam","all")
Which replacies both of these:
grape jelly
grape jellies
with this:
grape jam
but this doesn't match:
pear jelly

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/coldfusion/7/htmldocs/00000985.htm