# Regex\_replace behavior changes when multi-line string used

**URL:** <https://forum.ansible.com/t/regex-replace-behavior-changes-when-multi-line-string-used/39767>\
**Category:** Get Help\
**Tags:** template\
**Created:** [January 22, 2025, 3:11pm UTC](https://forum.ansible.com/t/regex-replace-behavior-changes-when-multi-line-string-used/39767 "2025-01-22T15:11:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pabigot](https://avatars.discourse-cdn.com/v4/letter/p/7feea3/32.png) [@pabigot](https://forum.ansible.com/u/pabigot)\
**Post date:** [January 22, 2025, 3:11pm UTC](https://forum.ansible.com/t/regex-replace-behavior-changes-when-multi-line-string-used/39767/1 "2025-01-22T15:11:14Z")

</div>

Using Ansible 2.18.1 core, this command:

```
ansible-playbook repro.yml

```

with this playbook:

```auto
- name: Run the test play
  hosts: 127.0.0.1
  connection: local
  tasks:
    - name: Map issue
      delegate_to: localhost
      vars:
        wai1: "{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}"
        wai2: >-
          {{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
      ansible.builtin.debug:
        msg:
          - "{{ wai1 }}"
          - "{{ wai2 }}"

```

produces this result:

```auto
TASK [Gathering Facts] *********************************************************************************************************************************
ok: [127.0.0.1]

TASK [Map issue] ***************************************************************************************************************************************
ok: [127.0.0.1 -> localhost] => {
    "msg": [
        "able",
        "a\\1"
    ]
}

```

The template, taken from the first example in the [filter documentation](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/regex_replace_filter.html) is the same in both variables, but the output is not correct in the multi-line template.

Can somebody tell me what’s going on, and how I can make this filter work in a multi-line string?

Thanks!

---

<div class="post-metadata">

**Author:** ![pabigot](https://avatars.discourse-cdn.com/v4/letter/p/7feea3/32.png) [@pabigot](https://forum.ansible.com/u/pabigot)\
**Post date:** [January 22, 2025, 3:27pm UTC](https://forum.ansible.com/t/regex-replace-behavior-changes-when-multi-line-string-used/39767/2 "2025-01-22T15:27:27Z")

</div>

[This related topic](https://forum.ansible.com/t/regex-replace-filter-is-not-working/22730) provided the answer: multiline automatically escapes `\` so this change works:

```
    wai2: >-
      {{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\1') }}

```
