【问题标题】:How to print matching strings in python with regex?如何使用正则表达式在python中打印匹配的字符串?
【发布时间】:2021-07-12 19:05:50
【问题描述】:

我正在编写一个 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=r'^[\w&.-]+$'
  • 感谢您的建议!我不得不进一步更改正则表达式以匹配我必须分析的文件的特异性,我已经用最终脚本更新了原始问题。

标签: python python-3.x regex


【解决方案1】:

根据文档,正则表达式模块的 match() 搜索“字符串开头的字符 [与正则表达式模式匹配的字符”。由于您在文件内容前面加上文件名:

content=fname + f_contents

然后match将您的模式与该行中的content 对比:

result=re.match(regex, content)

永远不会有比赛。

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

另见:search() vs match()

编辑

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

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

同时匹配这两个字符串的模式可能是:

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

Try it out here

【讨论】:

  • 有道理,感谢您的建议!但是,更新后的代码仍然存在问题,它仍在打印“Nothing found”行。我已经用我所做的更改更新了上面的代码(包括你提到的 re.search 以及另一个用户建议的正则表达式更新)
  • 您提供的正则表达式既不匹配 serial number = 642E0523D775,因为它包含空格 (" "),也不匹配 max-limit=50M/50M,因为它包含正斜杠 ("/")。这是您提供的样品的错误吗?否则,请参阅我的答案的编辑以获取可以匹配这些字符串的模式。
  • 感谢您的建议!我最终使用了 re.findall,因为它更适合我的需要。另外,我的正则表达式肯定是错误的,使用匹配器帮助我把它弄对了。我用最终脚本更新了我的问题,如果你感兴趣的话,我需要它。
猜你喜欢
  • 2013-09-16
  • 1970-01-01
  • 2023-04-02
  • 2020-11-29
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
相关资源
最近更新 更多