簡體   English   中英

使用ansible和regex_replace過濾器提取字符串的最后一個字符

[英]Extract last character of string with ansible and regex_replace filter

在劇本中,我嘗試提取變量“ansible_hostname”的最后一個字符。

我嘗試使用regex_replace過濾器來做到這一點,但沒有任何作用。

我用這個ad-hoc命令簡化了我的腳本:

ansible localhost -m debug -a“msg = {{'devserver01'| regex_replace('[0-9] {1} $','\\ 1')}}”

我想提取最后一個字符:'1'。

我正在使用Ansible 2.0。

Python可以節省一天,並且在這種使用中是可以接受的。

只需在字符串或變量的末尾添加[-1],它將獲取字符串中的最后一個字符。

ansible localhost -m debug -a "msg={{ 'devserver01'[-1] }}"

以下內容適合您。

ansible localhost -m debug -a "msg= {{ 'devserver01' | regex_replace('^(.+)([0-9]{1})$','\\1') }}"

說明:

^(.+) : it will take one or more group of characters from start
([0-9]{1})$ : removes one digit from end of string

\\1 : is a back reference to the first group

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM