【问题标题】:Using regex_search to extract a string between a string and a whitespace使用 regex_search 提取字符串和空格之间的字符串
【发布时间】:2021-09-27 13:52:08
【问题描述】:

我想从 Ansible 中的以下字符串中提取版本号 1.0.1,我尝试使用 regex_serach 在 ide- 和空格之间添加额外的字符串,但这就是我最终得到的 ide-1.0.1 ; argv[]=/home/bin/ide-1.0.1 start。我尝试了\s 而不是\\s,但它不起作用。我应该如何修复正则表达式模式?任何帮助将不胜感激!

ExecStart={ path=/home/bin/ide-1.0.1 ; argv[]=/home/bin/ide-1.0.1 start }
- name: Check if ide is active
  command: systemctl show ide.service --property=ExecStart
  register: version_check
  ignore_errors: yes

- name: Set fact
  set_fact:
    version: "{{ version_check.stdout | regex_search('ide-(.*)\\s'}}"


- name: Debug version
  debug:{{ version }}"

【问题讨论】:

  • regex_search('ide-([^ ]+).*','\\1') 应该够了!

标签: regex ansible regex-group


【解决方案1】:

使用 regex_replace,例如

    - set_fact:
        version: "{{ _path.split('-').1 }}"
      vars:
        _regex: '^(.*)=(.*)=(.*);(.*)$'
        _replace: '\3'
        _path: "{{ version_check.stdout|regex_replace(_regex, _replace)|trim }}"

给予

  version: 1.0.1

Parsing semi-structured text with Ansible 可用,例如

    - ansible.utils.cli_parse:
        text: "{{ version_check.stdout }}"
        parser:
          name: ansible.netcommon.native
          template_path: templates/property.yaml
        set_fact: property

和模板

shell> cat templates/property.yaml
---
- example: 'ExecStart={ path=/home/bin/ide-1.0.1 ; argv[]=/home/bin/ide-1.0.1 start }'
  getval: '(?P<property>\S+)={\s*(?P<key1>\S+)=(?P<val1>\S+)\s*;\s*(?P<key2>\S+)=(?P<val2>\S+)\s*(?P<state>\S+)\s*}'
  result:
    "{{ property }}":
      "{{ key1 }}": "{{ val1 }}"
      "{{ key2 }}": "{{ val2 }}"
      state: "{{ state }}"

  property:
    ExecStart:
      argv[]: /home/bin/ide-1.0.1
      path: /home/bin/ide-1.0.1
      state: start

然后解析版本,例如

    - set_fact:
        version: "{{ (property.ExecStart.path|basename).split('-').1 }}"

给予

  version: 1.0.1

【讨论】:

  • 感谢您的意见。是否可以简单地通过 regex_research 来做到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
相关资源
最近更新 更多