python - 如何在 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)
解决方案
一个正则表达式应该可以。共同的线程似乎是全大写的 alpha,从后面跟着的东西开始TEC_
,更多的 alpha 和一个数字,所以......
[A-Z]+TEC_[A-Z]+[0-9]+
请参阅https://regexr.com/3qveu进行测试。
推荐阅读
- javascript - Reactjs:如何使用旋转图片库添加下一个/上一个按钮
- mysql - 带参数的存储过程
- java - 如何在 Java 中捕获所有传入的 gRPC 消息?
- java - Java OAuth 2.0 通过带有客户端 ID 和密码的 HTTP GET 获取访问令牌
- django - 在 Django 中的 post save 信号中发送电子邮件的问题
- json - 如何在 Swift for MacOS 中解析来自 Yahoo Finance 的 JSON
- selenium - 如何在 xpath 中使用撇号 (')?
- node.js - JWT 签名令牌过期即使在代码中更改后浏览器应用程序中也不会更改
- php - 相关模型返回集合时如何访问子相关模型
- pandas - 如何比较两个数据帧以推断第三个数据帧