Discussion:
REReplace question
(too old to reply)
ixuzus
2009-03-29 23:24:32 UTC
Permalink
I'm trying to remove everything between { and } in a string. I can do it using
an ugly combination of FIND, MID, and a loop but suspect there might be an
easier option using REReplace. Unfortunately I'm having trouble getting it to
work.

For example I'm looking to turn this:

Some text {some more text} even more text { too much text } enough text.

into this:

Some text even more text enough text.

If someone could show me how to do this and, if possible, give a brief
explanation of how it works that would be much appreciated.
craigkaminsky
2009-03-30 01:14:22 UTC
Permalink
This might not be an ideal regular expression but it seems to get the job done:

<cfscript>
mystring = "Some text {some more text} even more text { too much text }
enough text.";
mynewstring = ReReplace( mystring, '{[\w\d\s]*}', '', 'ALL' );
</cfscript>
<cfoutput>#mynewstring#</cfoutput>

Using ReReplace (you could also use ReReplaceNoCase), we first pass it the
string to which we will apply the pattern (regexp).

The second parameter is the pattern: {[\w\d\s]*}
This pattern first locates a left brace ( { ).

Then we tell CF to look for a group, which is defined inside the brackets ( [
] ). I'm guessing that you won't know what text will be between the braces
(i.e., if it's one word, two words, spaces, numbers, etc.). As such, the \w
instructs CF to look for any word, \d indicates digits, and \s indicates
whitespace (tabs, newlines, etc.). CF will search for any or all of these in
the string, just to the right of the left brace.

We add a qunatifier next to the right bracket ( ]* ). This says "match all or
none" in our group.

Next, we end the regexp with the right brace ( } ). Now, any variation of word
or words, number or numbers or any kind of whitespace between two braces will
be found/matched.

The third parameter of ReReplace is the replacement string (aka substring). I
left this blank ( '' ) so that the text is removed from the string.

Finally, we use the fourth parameter of ReReplace to instruct CF to remove all
instances found.

Hope that helps!
ixuzus
2009-03-30 06:19:19 UTC
Permalink
That helps a lot.

Thank you very much.

Loading...