---
title: "Insert text literally when you replace · Agent Wranglers"
url: https://agentwranglers.se/playbook/architecture/data-shapes/literal-replacement
updated: 2026-10-20
licence: "All rights reserved"
---

# Insert text literally when you replace

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Data shapes](https://agentwranglers.se/playbook/architecture/data-shapes)
- Rule: When you insert outside text with a replace function, make sure the text goes in exactly as written. Many replace functions treat parts of the replacement as commands.
- How: In a replacement string, `$&`, `$1` or `\1` mean "the matched text" or "group 1". Content that happens to contain them comes out mangled. Pass a callback that returns the text, or use the language's quoting helper. A plain substring replace without patterns is also safe.
- Check: Insert the text `$& $1 \1 $'` through every template or replace step. The output contains those characters unchanged.

Example:

```js
// JavaScript: $&, $1 and $' are special in a replacement string
page.replace('<!--body-->', html);        // Bad
page.replace('<!--body-->', () => html);  // Good: a function is inserted as is
```

```python
# Python: \1 and \g<0> are special in re.sub's replacement string
re.sub(r"<!--body-->", html, page)            # Bad
re.sub(r"<!--body-->", lambda m: html, page)  # Good
```

```php
// PHP: $1 and \1 are special in preg_replace's replacement
preg_replace('/<!--body-->/', $html, $page);                          // Bad
preg_replace_callback('/<!--body-->/', fn($m) => $html, $page);       // Good
```

```java
// Java: $ and \ are special in replaceAll's replacement
page.replaceAll("<!--body-->", html);                            // Bad
page.replaceAll("<!--body-->", Matcher.quoteReplacement(html));  // Good
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers architecture playbook: https://agentwranglers.se/playbook/architecture/data-shapes/literal-replacement`.

- Previous: [Give each function one return type](https://agentwranglers.se/playbook/architecture/data-shapes/one-return-type)
- [Data shapes](https://agentwranglers.se/playbook/architecture/data-shapes)
