正则表达式匹配括号

正则表达式匹配括号

本文介绍了Ansible 正则表达式匹配括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要匹配一个字符串 NAME ALL=(ALL) NOPASSWD: ALL但是我被括号卡住了.

I need to match a string NAME ALL=(ALL) NOPASSWD: ALLHowever I'm getting stuck with the parenthesis.

我使用了一个网站来帮助我构建表达式,但我无法弄清楚.到目前为止,我得到了:\sNAME\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL但是,没有得到括号符号......我还使用了大量 \s,我确定有更好的方法吗?

I used a website to help me build the expression but am unable to figure it out.Thusfar I got:\sNAME\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALLHowever that doesn't get the parenthesis signs...Also I use a ton of \s, which I'm sure there is a better way for?

我正在使用 Ansible Lineinfile 模块来删除该行.感谢所有帮助,谢谢!

I'm using the Ansible Lineinfile module to remove the line.All help is appreciated, thank you!

以防万一,我的小剧本补充说,可能是我在那里做错了什么:

Just in case, my little playbook added, might be that I do something wrong there:

嗨.

是的,它在所有这些生成器中都匹配,但无论出于何种原因,我都无法在我的剧本中使用它,我是这样的白痴还是?

Yeah it matches in all those generators, but for whatever reason I can't get it working in my playbook, am I such an idiot or?

- hosts: all
  become: true
  tasks:
  - name: Remove user
    lineinfile:
      dest: /etc/sudoers
      regexp: '^.*NAME.*$'
      state: 'absent'

推荐答案

  • 你需要用 \ 转义 ();
  • 字符串中的空格与正则表达式中的空格匹配;
  • 您可以在 ^$(或其中之一)之间编写表达式,以确保它只匹配确切的行(不是注释掉的行,例如).
    • You need to escape ( and ) with \;
    • a space in the string is matched by a space in the regular expression;
    • you can write the expression between ^ and $ (or just one of them) to be sure it matches only the exact line (not a commented-out line, for example).
    • 要匹配问题中的确切行:

      To match the exact line from the question:

      regexp: '^NAME ALL=\(ALL\)       NOPASSWD: ALL$'
      

      您还可以使用带有乘数的 \s 来匹配随机长度的空格,例如在 NOPASSWD 字符串之前:


      You can also use \s with a multiplier to match a random-length whitespace, for example before NOPASSWD string:

      regexp: '^NAME ALL=\(ALL\)\s*NOPASSWD: ALL$'
      

      但是

      您正在尝试修改 /etc/sudoers ― 花一些时间阅读 编辑是否安全带有 Ansible lineinfile"的/etc/sudoers模块?,尤其是这个答案.


      BUT

      You are trying to modify /etc/sudoers ― take some time to read Is it safe to edit /etc/sudoers with the Ansible "lineinfile" module? and particularly this answer.

      这篇关于Ansible 正则表达式匹配括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:44