Deleting single or double quotation marks in a string using REGEX

Hello,

Here is my playbook.

- name: Remove Quotes from Variable
  hosts: localhost
  gather_facts: false
  vars:
    original_text: "this is \"Hello'World\""

  tasks:
    - name: Display Original Text
      debug:
        var: original_text

    - name: Remove Quotes and Update Variable
      set_fact:
        original_text: "{{ original_text | regex_replace('[\"]', '') }}"

    - name: Display Updated Text
      debug:
        var: original_text

The task is to remove all existing single or double quotation marks in a string.

The problem is that with the current regex, only the double quotation marks in the string are deleted.

However, if I change the regex in this way regex_replace('[\'\"]', ''), I receive an error message. Therefore, my question is: What regex is correct for this task?

This is one of those “regex is not intuitive” things.

First off, I don’t think you need to use regex_replace, you can just use replace.

But either way, you need to put the single quote inside double quotes, and escape the double quotes. I know, why? I don’t know LOL.

So the updated line that would include both replaces - I am showing both regex_replace and replace, same syntax for both:

original_text: "{{ original_text | regex_replace('\"', '') | regex_replace(\"'\", '') }}"
original_text: "{{ original_text | replace('\"', '') | replace(\"'\", '') }}"
1 Like

The right way to escape single-quotes in single-quoted YAML strings is to double them, regex_replace('[''\"]', '')

But this won’t fix it inline because Jinja2 rendering removes the single quotes:

>>> from jinja2.nativetypes import NativeEnvironment
>>> e = NativeEnvironment()
>>> t = e.from_string('[''"]')
>>> t.render()
'["]'

So this would be a time where I simplify with a task var.

    - name: Remove Quotes and Update Variable
      set_fact:
        original_text: "{{ original_text | regex_replace(re_match, '') }}"
      vars:
        re_match: >-
          ['"]
        # or
        # re_match: '[''"]'
        # re_match: "['\"]"
3 Likes

Hi,

thanks for your answer, I’ve tested your code and it works as expected.

Hi,
thanks for your answer,
I didn’t know this approch but
I’ve tested your code and it works as expected.