Ansible: Match Special Characters Without Escaping

Ansible provides a rich pattern matching ability. Modules like lineinfile can match strings based on regular expressions. Similar expressions are used in Python, Perl and older tools such as egrep, grep, sed and awk.

When attempting to match a string containing awkward characters, an escape mechanism can be used. For example, the dollar character ($) has a special meaning within in a regular expression, being the match for end-of-line. So to match a literal dollar, an escape character, usually a backslash (\), is needed. For example, the regular expression “\$1.65” will successfully match $1.65, without treating $ as end of line.

When processing a string that contains many special characters, the escape syntax can become onerous. One solution is to just “blanket” match the special character, rather than trying to match it precisely. In other words: just use a dot. Continue reading