繁体   English   中英

如何使用正则表达式在python中打印匹配的字符串?

[英]How to print matching strings in python with regex?

我正在开发一个 Python 脚本,该脚本将遍历包含一堆文件的目录并提取与特定模式匹配的字符串。 更具体地说,我试图提取序列号和最大限制的值,这些行看起来像这样:

#serial number = 642E0523D775

max-limit=50M/50M

我有脚本来检查文件,但我在实际打印我想要的值时遇到了问题。 我没有打印值,而是得到“Nothing fount”输出。

我认为它可能与我正在使用的正则表达式有关,但我一生都无法弄清楚如何制定它。

到目前为止我想出的脚本:

import os
import re

#Where I'm searching

user_input = "/path/to/files/"
directory = os.listdir(user_input)

#What I'm looking for

searchstring = ['serial number', 'max-limit']
re_first = re.compile ('serial.\w.*')
re_second = re.compile ('max-limit=\w*.\w*')

#Regex combine
regex_list = [re_first, re_second]

#Looking

for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        # Full path
        f = open(user_input + os.sep + fname, 'r')
        f_contents = f.read()
        content = fname + f_contents
        files = os.listdir(user_input)
        lines_seen = set()

        for f in files:
         print(f)
         if f not in lines_seen:  # not a duplicate

          for regex in regex_list:
              matches = re.findall(regex, content)

              if matches != None:
                for match in matches:
                  print(match)
              else:
                  print('Nema')
        f.close()

根据文档,regex 模块的match()搜索“字符串开头的字符 [that] 匹配正则表达式模式”。 由于您在行中使用文件名预先添加文件内容:

content=fname + f_contents

然后match您的模式与行中的content进行match

result=re.match(regex, content)

永远不会有比赛。

由于您想在字符串中的任何位置定位匹配项,请改用search()

另请参阅:search()match()

编辑

提供的模式^[\\w&.\\-]+$既不匹配serial number = 642E0523D775因为它包含空格 (" "),也不匹配max-limit=50M/50M因为它包含一个正斜杠 ("/")。 两者还包含一个等号 ("="),您的模式无法匹配该等号。

此外,此模式中的字符类与反斜杠 ("") 匹配,因此您可能希望将其删除(破折号 ("-") 在字符类的末尾时不应转义)。

匹配这两个字符串的模式也可以是:

^[\\w&. \\/=\\-]+$

在这里试试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM