【问题标题】:Regex to match '#attribute value' or 'attribute value' of linux configuration files but not '# a comment'正则表达式匹配 linux 配置文件的“#attribute value”或“attribute value”,但不匹配“#a comment”
【发布时间】:2016-10-14 15:05:15
【问题描述】:

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 正则表达式代码来识别在 # 之后没有空格的注释行(因此它们不是真正的 cmets),还有未注释的行,例如 attribute value。写这个正则表达式很困难。我试着开始:

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

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

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

它将匹配Use these,这不是我想要做的。我搜索了(?=),它将匹配它之前的内容,只有当它后面跟着这个条件时,但我没有成功。任何帮助表示赞赏。

【问题讨论】:

  • 在你的正则表达式的开头放一个^,这样它就只匹配一行的开头。

标签: python regex linux


【解决方案1】:

您可以使用否定前瞻断言:

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

【讨论】:

  • 你的正则表达式究竟是如何工作的?匹配不以 # 和空格开头的任何内容?除了前面的换行符之外还有其他字符吗?
  • @Gatonito 添加了简短的解释,希望对您有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
相关资源
最近更新 更多