RegEx for matching numbers in Twig

Asked by At

I have a route like this

admin/applicants/1111/view

I try to catch that route in twig like this:

{% if route  matches '#admin\/applicants\/\d+\/view#' %}
      route matched
{% else %}
      not matched 
{% endif %}

It should match, have tested and it works perfectly.

How do I solve this problem?

2 Answers

2
DarkBee On Best Solutions

While Emma's answer is correct, keep in mind that you would need to "escape" the backslash in front of \d otherwise twig will translate to \d to a literal d in the source code

{% if route  matches '#admin\/applicants\/\\d+\/view#' %}
      route matched
{% else %}
      not matched 
{% endif %}

{% if route  matches '#admin\/applicants\/\d+\/view#' %}

Compiled PHP source

if (preg_match("#admin/applicants/d+/view#", (isset($context["route"])

As you can see the compiled php source translate just to d+. Adding an extra backslash "solves" this issue (see code above line)

2
Emma On

You might just want to use [0-9] instead of \d, and it would probably solve your problem:

Code:

{% set route = 'admin/applicants/1111/view' %}
{% if route  matches '#admin\/applicants\/[0-9]+\/view#' %}
    route matched
{% else %}
    not matched 
{% endif %}

Output

route matched