Home > Back-end >  regex expression in jinja2
regex expression in jinja2

Time:12-13

I have a jinja2 script with a for loop, I just want to see if there is any way I can use regex checks in an if statement. So the script looks like:

{% for key, value in notes.items() -%}
if {{ value }} starts with http or https
then ~*^/{{ key }}(\?.*)?$ {{ value }};
otherwise
~*^/{{ key }}(\?.*)?$ /{{ value }};
{% endfor %}

Is that somewhow writable???

CodePudding user response:

For example,

- hosts: localhost
  gather_facts: false
  vars:
    _dict:
      k1: v1
      k2: https://example.com
      k3: http://example.com
  tasks:
    - debug:
        msg: |
          {% for key, value in _dict.items() -%}
          {% if value is regex('^(http|https).*$') %}
          ~*^/{{ key }}(\?.*)?$ {{ value }};
          {% else %}
          ~*^/{{ key }}(\?.*)?$ /{{ value }};
          {% endif %}
          {% endfor %}

gives

  msg: |-
    ~*^/k1(\?.*)?$ /v1;
    ~*^/k2(\?.*)?$ https://example.com;
    ~*^/k3(\?.*)?$ http://example.com;

Notes

Q: "No test named 'regex' found."

See Testing strings. The test match gives the same result

    - debug:
        msg: |
          {% for key, value in _dict.items() -%}
          {% if value is match('(http|https)') %}
          ~*^/{{ key }}(\?.*)?$ {{ value }};
          {% else %}
          ~*^/{{ key }}(\?.*)?$ /{{ value }};
          {% endif %}
          {% endfor %}

Q: "The same result with 'match' and 'search'."

A: Test the first 4 characters of the value

         {% if value[:4] == 'http' %}
  • Related