Reputation: 4284
Here is my regex to detect expressions like {{ value1 | value2 }}
:
p="\{{\{{\s*{tag_key}\s*([^\|\}}]+)\s*\|\s*([^\|\{{]+)\s*\}}\}}".format(tag_key="name")
It's totally fine where there are some spaces between value1
In [1]: re.sub(p, "REPLACED", "content: {{ name |default_value}}")
Out[1]: 'content: REPLACED'
Or
In [2]: re.sub(p, "REPLACED", "content: {{ name |default_value}}")
Out[2]: 'content: REPLACED'
But what I want is my pattern acts the same either there are spaces or not.
In [3]: re.sub(p, "REPLACED", "content: {{name|default_value}}")
Out[3]: 'content: {{name|default_value}}'
Any help would be appreciated!
Upvotes: 0
Views: 52
Reputation: 6053
It wasn’t working without spaces because you had an extra ([^\|\}}]+)
that you didn’t need, which was requiring a space to be present. Here’s what I would recommend:
p = r"{{\s*" + tag_key + r"\s*\|\s*([^\|}]+)\s*}}"
This way the braces {}
from the Python string format function don’t have a chance to throw you off either.
Upvotes: 1