Applies a regular expression operation on the input. This filter requires two values: the first is the pattern and the second is the replacement. Learning regular expressions is outside the scope of this document, though it is likely helpful to know that Perl-style regular expressions are supported. RegExr is a tool for learning, testing, and sharing regular expressions; a desktop version also available.
Note that if you don’t need regular expression support, the
replace modifier is simpler and faster.
As noted above, the
replace modifier is a better choice when a simple text search and replace is needed. An example of an operation better handled by
replace is stripping the “.html” extension from URLs. Simply, a regular expression is not needed to do this type of search:
This would strip any bracketed phrase from the end of the entry title field:
Back references can be used in the replacement, such as this example that prints the first three words (if available, but at least 1) in the Entry Title:
Regex modifiers are supported. The global modifier, for example, will find all occurrences of bracketed phrases and remove them:
Or, a case-insensitive search to strip the word “apple” from text (in other words, it would find “Apple” or “aPpLlE”):
If blog description is:
<strong>I am the walrus</strong> <em>(Koo Koo Ca Choo)</em>
regex_replace to get the part in parenthesis:
Output will be:
<em>Koo Koo Ca Choo</em>
Movable Type can get confused if the pattern string contains double quotes. It is best to define the pattern and replacement strings as variables, and reference those variables as the
For example, the old name of your company, ACME “Widgets” Inc., might be strewn across your entries. But now that your company is called Widget Masters Inc., you might want to automatically replace the name in the output till you can find the time to do a quick “Search & Replace” on the entries.
<mt:SetVarBlock name="pattern">/ACME "Widgets" Inc/g</mt:SetVarBlock> <mt:SetVarBlock name="replacement">Widget Masters Inc</mt:SetVarBlock> <mt:EntryBody regex_replace="$pattern","$replacement">
You can do multiple regex replacements using different variable names. Note the modifiers are processed in order from left to right.
<mt:SetVarBlock name="p1">/ACME "Widgets" Inc/g</mt:SetVarBlock> <mt:SetVarBlock name="r1">Widget Masters Inc</mt:SetVarBlock> <mt:SetVarBlock name="p1">/AWI/g</mt:SetVarBlock> <mt:SetVarBlock name="r1">WMI</mt:SetVarBlock> <mt:EntryBody regex_replace="$p1","$r1" regex_replace="$p2","$r2">