Twig has a 'replace' filter but it does not support regex patterns. But you can overwrite the filter with your own method. See this page for details on how to add your own twig filters https://octobercms.com/docs/plugin/registration#extending-twig
public function replaceFilter($str, $search, $replace = null)
{
// Are they using the standard Twig syntax?
if (is_array($search) && $replace === null)
{
return strtr($str, $search);
}
// Is this a regular expression?
else if (preg_match('/^\/.+\/[a-zA-Z]*$/', $search))
{
return preg_replace($search, $replace, $str);
}
else
{
// Otherwise use str_replace
return str_replace($search, $replace, $str);
}
}