【问题标题】:python - print line and list that contains regex matchpython - 打印包含正则表达式匹配的行和列表
【发布时间】:2016-09-22 02:08:46
【问题描述】:

我有一个日志文件,至少有一千行

abc.txt:
1. example eg, ham, cheese 350.122.345.8
2. cheese ham eg, example 231.242.1.2
3. Ham cheese, example,e.g 100.200.100.200
4.
5. Ham cheese, example,e.g 100.200.100.200
1000. 

我想要的最终结果:

仅打印与 IP 地址范围内的数字匹配的行。因此它应该只打印:

2. cheese ham eg, example 231.242.1.2
3. Ham cheese, example,e.g 100.200.100.200
5. Ham cheese, example,e.g 100.200.100.200

我尝试了以下代码,但无法得到我想要的结果:

import re

txt=open('/sdcard/Download/abc.txt','r')

pattern=re.compile('(^[2][0-5][0-5]|^[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})$', re.DOTALL)

for line in txt:
    if str(pattern) in line:
        print line
    else:
        print 'WRONG LINE:',line

返回的结果是打印出的完整行列表并显示我的 else WRONG LINE 消息。

我用在线检查器检查了我的正则表达式,它显示了正确的行为,匹配所有不超过 .255 的 ipv4 地址

请指出错误。

【问题讨论】:

  • str(pattern) in line 不是你想要的。你需要re.searchre.match 之类的东西。
  • if re.search(pattern, line) print bla
  • 如果你使用编译模式,你必须使用它的搜索或匹配方法。 docs.python.org/2/library/re.html#re.compile
  • 另外,你也可以 print(str(pattern)) 看看这不是你想要的
  • @rock321987 应该类似于if pattern.search(line): print line

标签: python regex ip-address ipv4


【解决方案1】:

来自:@RudyTheHunter

import re

txt=open('/sdcard/Download/abc.txt','r')

pattern=re.compile('([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})', re.DOTALL)

for line in txt:
    if pattern.search(line):
        print line
    else: 
        print 'WRONG LINE:',line

【讨论】:

    【解决方案2】:

    这是更正后的正则表达式和代码:

    import re
    
    txt= {"1. example eg, ham, cheese 350.122.345.8",
          "2. cheese ham eg, example 231.242.1.2",
          "3. Ham cheese, example,e.g 100.200.100.200",
          "4.",
          "5. Ham cheese, example,e.g 100.200.100.200"}
    
    
    pattern=re.compile('([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})', re.DOTALL)
    
    for line in txt:
        if pattern.search(line):
            print line
        else:
            print 'WRONG LINE:',line
    

    【讨论】:

      猜你喜欢
      • 2014-09-10
      • 2015-02-24
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多