我试图在一行中的 1 个空格之后找到一个字符串,如果存在,则提取完整的行并存储在不同的变量中。我正在使用 ansible 和正则表达式。如果该字符串存在于任何其他位置,则不应匹配它。
我尝试使用 regex_match 和 select 但出现错误。
vars:
input : "{{ lookup('template', '{{ file }}') }}"
target: "{{ input | regex_search('^(?=.*\b INPUT\b)(?:\S+){1}(\S*.*)')}}"
Run Code Online (Sandbox Code Playgroud)
错误总是出现在同一位置“(?:\S+)”。
ERROR! Syntax Error while loading YAML.
found unknown escape character 'S'
The offending line appears to be:
input : "{{ lookup('template', '{{ file }}') }}"
target: "{{ input | regex_search('^(?=.*\b INPUT\b)(?:\S+){1}(\S*.*)')}}"
^ here
Run Code Online (Sandbox Code Playgroud)
input : "{{ lookup('template', '{{ file }}') }}"
target: "{{ input | select('match', '^(?=.*\b INPUT\b)(?:\S+){1}(\S*.*)' | list | first}}"
^ here
Run Code Online (Sandbox Code Playgroud)
我还尝试包含 / 的转义字符,但也出现错误。
ERROR! Syntax Error while loading YAML.
found unknown escape character 'S'
The offending line appears to be:
input : "{{ lookup('template', '{{ file }}') }}"
target: "{{ input | regex_search('^(?=.*/\b INPUT/\b)(?:/\S){1}(/\S*.*)')}}"
^ here
Run Code Online (Sandbox Code Playgroud)
我的变量文件
-P INPUT ACCEPT
-A INPUT -s 1.1.1.1/32 -j ACCEPT
-A INPUT -s 2.2.2.2/32 -j ACCEPT
-A INPUT -s 3.3.3.3/32 -j ACCEPT
-A INPUT -j RH-Firewall
-N RH-Firewall
-A RH-Firewall -j INPUT
-A RH-Firewall -p icmp -m icmp --icmp-type 0 -j ACCEPT
-A RH-Firewall -p icmp -m icmp --icmp-type 3 -j ACCEPT
-A RH-Firewall-1 -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A RH-Firewall -p icmp -m icmp --icmp-type 11 -j ACCEPT
Run Code Online (Sandbox Code Playgroud)
target_rule_set 应仅包含前 5 行。同样,如果我匹配 RH-Firewall,那么它应该包含第 6-11 行。
您可以regex_findall使用multiline=True:
(?m)^\S+\s+INPUT\b.*
Run Code Online (Sandbox Code Playgroud)
请参阅正则表达式演示。细节:
^(?m)-自使用以来开始一行\S+- 1+ 个非空白字符\s+- 1+ 空格INPUT\b-INPUT作为一个完整的词.*- 该行的其余部分。在代码中:
target: "{{ input | regex_findall('^\\S+\\s+INPUT\\b.*', multiline=True)}}"
Run Code Online (Sandbox Code Playgroud)