【问题标题】:Group matches and non-matches from regular expressions来自正则表达式的分组匹配和不匹配
【发布时间】:2018-01-22 14:26:10
【问题描述】:

我正在处理的脚本目前在一个文件中执行三个正则表达式搜索;考虑以下作为输入:

2018-01-22 04.02.03: Wurk: 98745061 (12345678)
 Replies (pos: 2) are missing/not sent on assignment: Asdf (55461)

2018-01-22 04.02.03: Wurk: 98885612 (87654321)
 Gorp: 98885612 is not registered for arrival!
 Brork: 98885612 is not registered for arrival!

2018-01-22 04.02.08: Wurk: 88855521 (885052)
 Blam: 12365479 is not registered for arrival!
 Fork: 56564123 is not registered for arrival!

2018-01-22 04.02.08: Wurk: A0885521 (885052)
 Blam: 12365479 is not registered for arrival!
 Fork: 56564123 is not registered for arrival!

其中每个正则表达式根据行的日期以及 Wurk: 之后的第一个数字查找文件中的行,并收集 Wurk: 之后的八位数字/字符。

import time, glob, re
logpath = glob.glob('path\\to\\log*.log')[0]
readfile = open(logpath, "r")
daysdate = time.strftime("%Y-%m-%d")
nine = []
eight = []
seven = []
no_match = []
for line in readfile:
    for match in re.finditer(daysdate + r'.*Wurk: (9.{7})', line):
        nine.append(match.group(1))
    for match in re.finditer(daysdate + r'.*Wurk: (8.{7})', line):
        eight.append(match.group(1))
    for match in re.finditer(daysdate + r'.*Wurk: (7.{7})', line):
        seven.append(match.group(1))
print("\nNine:\n%s\n" % ",\n".join(map(str, nine)) +
   "\nEight:\n%s\n" % ",\n".join(map(str, eight)) +
   "\nSeven:\n%s\n" % ",\n".join(map(str, seven)) +
   "\nNo matches found:\n%s\n" % ",\n".join(map(str, no_match)))

这目前给出了以下输出:

Nine:
98745061,
98885612

Eight:
88855521

Seven:

No matches found:

现在,手头的问题是弄清楚如何制作一个匹配 Wurk: 之后的八个数字/字符的正则表达式,这些数字/字符在以前的任何正则表达式中都不匹配。因此,新的输出应该是:

Nine:
98745061,
98885612

Eight:
88855521

Seven:

No matches found:
A0885521

TL;DR

如何匹配与之前正则表达式的条件不匹配的正则表达式?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    正则表达式不用于对数据进行分组;它旨在查找数据。使用正则表达式提取值,然后使用代码对它们进行分组:

    seven, eight, nine, no_match = [], [], [], []
    
    wurk_map = {'7': seven,
                '8': eight,
                '9': nine}
    
    wurks = re.findall(r'(?<=Wurk: ).{8}', text)
    for wurk in wurks:
        wurk_map.get(wurk[0], no_match).append(wurk)
    
    print(seven)     # []
    print(eight)     # ['88855521']
    print(nine)      # ['98745061', '98885612']
    print(no_match)  # ['A0885521']
    

    【讨论】:

      猜你喜欢
      • 2010-10-01
      • 2017-04-10
      • 2019-01-13
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多