python - 正则表达式匹配 '#attribute value' 或 'attribute value' 的 linux 配置文件,但不匹配 '# a comment'

标签 python regex linux

Linux 有这些配置文件,例如 sshd_config:

# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
#A b
#Port 1234
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key

我正在编写一个简单的 python 正则表达式代码来标识在 # 之后没有空格的注释行(因此它们不是真正的注释)以及非注释行,例如 属性值。编写这个正则表达式很困难。我试着从以下开始:

#?[a-zA-Z0-9]+\s[a-zA-Z0-9]+

也就是说,注释符号是可选的,但我需要匹配一个具有 1 个或多个字母的单词(属性),后跟另一个具有一个或多个字母的单词(值)。但请注意:

# Use these options to restrict which interfaces/protocols sshd will bind to

它会匹配Use these,这不是我想做的。我搜索了 (?=),它将匹配它之前的内容,前提是它后面跟着这个条件,但是我没有成功。感谢您的帮助。

最佳答案

您可以使用否定先行断言:

re.findall('^(?!#\s).*', s, re.MULTILINE)

对于给定的问题输入,它将提供以下输出:

['',
 '#A b',
 '#Port 1234',
 '#ListenAddress ::',
 '#ListenAddress 0.0.0.0',
 'Protocol 2',
 'HostKey /etc/ssh/ssh_host_rsa_key',
 'HostKey /etc/ssh/ssh_host_dsa_key',
 'HostKey /etc/ssh/ssh_host_ecdsa_key']

更新 Negative lookahead assertation仅当下一个字符不匹配时才匹配。所以在上面 ^ 匹配到行的开头,因为使用了 re.MULTILINE。然后 (?!#\s) 匹配除 # 字符之外的所有内容,紧接着是空白字符。参见 regex101 demo .

关于python - 正则表达式匹配 '#attribute value' 或 'attribute value' 的 linux 配置文件,但不匹配 '# a comment',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37802570/

相关文章:

linux - 将 autogen.sh 与 ExternalProject_Add 结合使用

python - Azure 功能(消费 Linux 计划)无法与系统标识一起访问用于 zip 部署的存储帐户

python - 如何创建一个字典,其中键是列表中的元素,值是从 1 到 n 的数字?

python - 排除 django 查询集中的重复对象

python - 如何知道调用python脚本的目录?

regex - 正则表达式中的 Ansible 转义 *

c# - 如何匹配不同语言的数字?

java - 替换 Java 中第一次出现的特定模式

c - 这个夹板警告是什么意思,我可能做错了什么?

linux - Spyder:变量资源管理器不显示连接的远程内核的变量