首页 > 解决方案 > 如何在 Python 中为特定类型的字母数字单词创建正则表达式

问题描述

我正在寻找在 Python 中创建基于正则表达式的搜索的建议。我在服务器日志文件中有以下类型的字符串值,

2017-03-18 13:24:05,791 INFO [STDOUT] SUB 请求状态:重新提交 INBIOS_ABZ824
2017-03-12 13:24:05,796 INFO [STDOUT] SUB 提交状态:重新提交 INDROS_MSR656
2017-04-12 13:24:05,991 INFO [STDOUT] SUB 请求状态:重新提交 INHP_GSN848

我需要搜索日志并提取如下值,

2017-03-18 13:24:05,791 INBIOS_ABZ824
2017-03-12 13:24:05,796 INDROS_MSR656
2017-04-12 13:24:05,991 INHP_GSN848

我正在使用以下代码,但它提取了存在此类字符串的完整行(INBIOS_ABZ824)。我怎样才能从上面的日志中只提取指定的值,请分享你的想法。

import os
import re

# Regex used to match relevant loglines (in this case)

line_regex = re.compile(r"[A-Z]+IOS_[A-Z]+[0-9]+", re.IGNORECASE)


# Output file, where the matched loglines will be copied to
output_filename = os.path.normpath("output.log")
# Overwrites the file, ensure we're starting out with a blank file
with open(output_filename, "w") as out_file:
    out_file.write("")

# Open output file in 'append' mode
with open(output_filename, "a") as out_file:
    # Open input file in 'read' mode
    with open("ServerError.txt", "r") as in_file:
        # Loop over each log line
        for line in in_file:
            # If log line matches our regex, print to console, and output file
            if (line_regex.search(line)):
                print(line)
                out_file.write(line)

标签: pythonregex

解决方案


一个正则表达式应该可以。共同的线程似乎是全大写的 alpha,从后面跟着的东西开始TEC_,更多的 alpha 和一个数字,所以......

[A-Z]+TEC_[A-Z]+[0-9]+

请参阅https://regexr.com/3qveu进行测试。


推荐阅读