python中的“否定"模式匹配 [英] 'negative' pattern matching in python

查看:30
本文介绍了python中的“否定"模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入,

OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
.

我想提取所有输入除了包含"OK SYS 10 LEN 20" 以及包含单个 "." (点) 的最后一行.也就是说,我要提取以下内容

And I'd like to extract all of the input except the line containing "OK SYS 10 LEN 20" and the last line which contains a single "." (dot). That is, I want to extract the following

1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt.1234 /data/c13af4/f.txt

我尝试了以下方法,

for item in output:
    matchObj = re.search("^(?!OK) | ^(?!\\.)", item)
    if matchObj:
        print "got item "  + item

但它不起作用,因为它不产生任何输出.

but it does not work, as it does not produce any output.

推荐答案

查看实际操作:

matchObj = re.search("^(?!OK|\\.).*", item)

不要忘记将 .* 放在否定前瞻之后,否则您将无法获得任何匹配 ;-)

Don't forget to put .* after negative look-ahead, otherwise you couldn't get any match ;-)

这篇关于python中的“否定"模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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