Reputation: 61
I want to replace each “\n” with “ \n” But it shouldn’t replace in places like words having \n “C:\node” how to achieve this.
- set_fact:
Value: “{{Str.replace(“\n”,” \n”)}}”
Upvotes: 0
Views: 1618
Reputation: 68034
Use single-quoted strings and put both regex and replace into variables. Then you have to escape '\' only once. For example,
- debug:
var: value
vars:
str1: 'C:\node'
value: "{{ str1|regex_replace(regex, replace) }}"
regex: '\\n'
replace: ' \\n'
gives
value: 'C: \node'
If you put regex and replace in-line you have to escape twice because of the outside double-quotes. For example, the task below gives the same result
- debug:
var: value
vars:
str1: 'C:\node'
value: "{{ str1|regex_replace('\\\\n', ' \\\\n') }}"
You have to escape also twice if you double-quote regex and replace in variables. For example, the task below gives the same result
- debug:
var: value
vars:
str1: 'C:\node'
value: "{{ str1|regex_replace(regex, replace) }}"
regex: "\\\\n"
replace: " \\\\n"
Upvotes: 2
Reputation: 142
The newline character \n
is different than the two characters \
and n
, so inside your regex if you do not escape the \
of the newline character it should not match the character \
followed by n
For example, the regex \n
matches the newline character but nothing in "C:\node" while \\n
will match "C:\node"
You can try to experiment with regex yourself in regex101
Upvotes: 0