Reputation: 57
I need to extract SERVER1 from a string like this: directory/SERVER1-info.dat
According to regex101.com, this regex string correctly parses it: (?<=\/)(\w*)(?=-)
but in Ansible, "{{ filename | regex_search('?<=/')('\w*')('?=-') }}"
causes an error "found unknown escape character 'w'\n\n errors.
I've tried removing the single quotes and doing \\w
, all these give more templating errors.
Upvotes: 1
Views: 3027
Reputation: 67984
If you want to select the string between the slash /
and dash -
, the task below does the job
- debug:
msg: "{{ path|regex_replace(regex, replace) }}"
vars:
path: directory/SERVER1-info.dat
regex: '^(.*)/(.*)-(.*)$'
replace: '\2'
gives
msg: SERVER1
If you'd like to avoid regex the task below gives the same result
- debug:
msg: "{{ (path|basename).split('-').0 }}"
vars:
path: directory/SERVER1-info.dat
Upvotes: 2