简体   繁体   English

我正在尝试使用 regex_replace 命令提取子字符串。 我想在这里提取“SWIFTInward”

[英]I am trying to extract a substring using regex_replace command . I want to extract “SWIFTInward” here

I tried below code in Ansible我在 Ansible 中尝试了以下代码

---
- hosts: windows
  strategy: linear

  vars:
    war_file_path: F:\\Install\\IIBProjects\\DE\\WAR\\DE_SWIFTInward-202010.0.0.war

  tasks:
    - name: Get properties folder path for windows
      set_fact:
        endpointDetails: "{{ item | win_basename | regex_replace('\\\\(?:(?!\\\\).)*$', '') }}"
      with_items:
        - "{{ war_file_path }}"
      register: war_file_name
      when: ansible_os_family == "Windows"

Expect output : SWIFTInward期望输出SWIFTInward
Error output which i am getting : DE_SWIFTInward-202010.0.0.war我得到的错误输出DE_SWIFTInward-202010.0.0.war

The win_basename returns the file name without the directory details. win_basename返回没有目录详细信息的文件名。 So, your regex does not match it as it requires a \\ at the start.因此,您的正则表达式与它不匹配,因为它在开始时需要一个\\

You need你需要

endpointDetails: "{{ item | win_basename | regex_replace('^[^_]*_([^_-]+).*', '\\1') }}"

See the regex demo查看正则表达式演示

Or, use regex_search with a simple _([^_-]+)- regex :或者,将regex_search与简单的_([^_-]+)- regex 一起使用

endpointDetails: "{{ item | win_basename | regex_search('(?<=_)[^_-]+') }}"

Details细节

  • ^[^_]*_([^_-]+).* : ^[^_]*_([^_-]+).* :
    • ^ - start of a string ^ - 字符串的开始
    • [^_]* - zero or more chars other than _ [^_]* - 除_以外的零个或多个字符
    • _ - a _ char _ - 一个_字符
    • ([^_-]+) - Group 1 ( \\1 ): one or more chars other than _ and - ([^_-]+) - 第 1 组 ( \\1 ):除_-之外的一个或多个字符
    • .* - the rest of the string. .* - 字符串的其余部分。
  • (?<=_)[^_-]+ : (?<=_)[^_-]+ :
    • (?<=_) - a location in string that is immediately preceded with _ (?<=_) - 字符串中紧跟在_前面的位置
    • [^_-]+ - one or more chars other than _ and - . [^_-]+ - 除_-之外的一个或多个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试使用正则表达式提取文本,但无法正常工作 - I am trying to extract text using regex but it is not working 我第一次尝试在 Google 表格上使用正则表达式从给定的字符串中提取 substring。 我应该使用哪种 Regex 模式来这样做? - I am trying to extract a substring from a given string using Regex on Google Sheets for the first time. Which Regex pattern should I use to do so? :使用Java中的Regex提取和替换子字符串 - :Extract and Replace a substring using Regex in Java 使用正则表达式提取子字符串 - extract substring using regex 如何在Java中使用正则表达式从字符串中提取子字符串? - How can i extract substring from the string using regex in Java? 如何使用正则表达式或子字符串从字符串中提取文本? - How can I extract text from a string using regex or substring? 如何使用RegEx提取文档字符串的子字符串? - How can I extract the substring of a document string using RegEx? 使用ansible和regex_replace过滤器提取字符串的最后一个字符 - Extract last character of string with ansible and regex_replace filter Oracle regex_replace - 仅提取匹配的字符串 - Oracle regex_replace - extract only matched string 使用正则表达式提取子字符串 - Using a regex to extract a substring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM