正则表达式匹配括号 [英] Ansible regexp match parenthesis

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

问题描述

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

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

我使用一个网站来帮助我构建该表达式,但无法弄清楚.到目前为止,我得到了: \ sNAME \ sALL = \(ALL \)\ s \ 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:\sALL However 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 ―花费一些时间阅读编辑是否安全?/etc/sudoers和Ansible的"lineinfile",尤其是此答案.


      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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆