<p>Yes.</p>

<pre class="lang-twig prettyprint-override"><code>{{ 'this is a string'|replace('/this is a (string)/', 'This is another $1') }}
</code></pre>

<p>will output</p>

<pre><code>This is another string
</code></pre>

<p>When you pass something that looks like a regex into the <code>|replace</code> filter,  <a href="http://php.net/manual/en/function.preg-replace.php" rel="noreferrer"><code>preg_replace()</code></a> is called behind the scenes, so <code>|replace</code> can do anything <code>preg_replace()</code> can do.</p>

CC BY-SA 3.0
2017-03-07T20:09:59.093Z
Ah, thanks. I must somehow have had some typo in my code, as Craft threw an error on $1 when I tried initially.
haabe
CC BY-SA 3.0
2017-03-07T12:35:49.167Z
2017-03-07T12:35:49.167Z
Brandon Kelly
<p>I see Craft <a href="https://craftcms.com/docs/templating/filters#replace" rel="noreferrer">does support regex in replace search.</a> But there is no info on using regex groups, ie <code>string | replace('/this is a (string)/', 'This is another $1')</code>.</p>

<p>Is this feature implemented? If so - how?</p>

CC BY-SA 4.0
2020-08-15T12:21:51.047Z
Why can't I use the word boundaries?
/bWord/b is also finding
Gudehus
<replace><regex>
Does Craft / Twig support regex groups?
# Does Craft / Twig support regex groups?

(Asked by: username_0 on 2017-03-07)

I see Craft [does support regex in replace search.](https://craftcms.com/docs/templating/filters#replace) But there is no info on using regex groups, ie `string | replace('/this is a (string)/', 'This is another $1')`.

Is this feature implemented? If so - how?

**Tags:** replace, regex
> **Comments:**
> **username_1**: Why can't I use the word boundaries? /bWord/b is also finding  

---

## 1 answers

### Answer by username_2 on 2017-03-07. Score: 7 | Accepted answer

Yes.
{{ 'this is a string'|replace('/this is a (string)/', 'This is another $1') }}

will output
This is another string

When you pass something that looks like a regex into the |replace filter,  preg_replace() is called behind the scenes, so |replace can do anything preg_replace() can do.

> **Comments:**
> **username_0**: Ah, thanks. I must somehow have had some typo in my code, as Craft threw an error on $1 when I tried initially.  

---

