【问题标题】:Extract last character of string with ansible and regex_replace filter使用 ansible 和 regex_replace 过滤器提取字符串的最后一个字符
【发布时间】:2016-06-10 12:21:14
【问题描述】:

在剧本中,我尝试提取变量“ansible_hostname”的最后一个字符。

我尝试使用 regex_replace 过滤器来做到这一点,但没有任何效果。

我用这个临时命令简化了我的脚本:

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

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

我正在使用 Ansible 2.0。

【问题讨论】:

  • 你想从devserver01中提取1
  • 看起来你正确匹配了最后一个字符(\d)$,但是你正在用它自己替换1,所以没有影响???
  • 是的,我知道,我离正则表达式大师还很远 :)
  • 如果您的目标只是获取最后一个字符,您可以执行 ^.*(\d)$ 并保留 \1

标签: regex ansible ansible-ad-hoc


【解决方案1】:

Python 可以节省时间,并且在这种用途中是可以接受的。

只需在字符串或变量的末尾添加一个 [-1],即可获取字符串中的最后一个字符。

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

【讨论】:

    【解决方案2】:

    以下内容对你有用。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      相关资源
      最近更新 更多