我正在寻找在Python中创建基于正则表达式的搜索的建议。在服务器日志文件中有以下类型的字符串值
2017-03-18 13:24:05791信息[STDOUT]子请求状态:重新提交INBIOS\u ABZ824
2017-03-12 13:24:05796信息[STDOUT]子提交状态:重新提交INDROS\u MSR656
2017-04-12 13:24:05991信息[STDOUT]子请求状态:重新提交INHP\u GSN848
我需要搜索日志并提取如下值
2017-03-18 13:24:05791英比奥斯ABZ824
2017年3月12日13:24:05796 INDROS\u MSR656
2017-04-12 13:24:05991英国邮政编码:GSN848
我使用下面的代码,但是它提取了完整的行,其中包含了类似的字符串(INBIOS\u 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)
我们终于找到了完美的答案。它将只提取所需的字符串,并消除与模式相关的其他值。你知道吗
在这里,我用另一个优化搜索结果重新匹配()在其最终发送到outfile之前调用。你知道吗
您可以匹配一个或多个大写字符
[A-Z]+
、下划线_
,然后匹配零个或多个[A-Z]*
次大写字符,后跟一个或多个数字[0-9]+
。你知道吗Use可能使用word boundary
\b
,因此它不是长匹配的一部分。你知道吗\b[A-Z]+_[A-Z]*[0-9]+\b
Regex demo
一个regexp就可以了。常见的线程似乎都是大写字母alpha,以
TEC_
开头,后面是字母和数字,所以。。。你知道吗参见https://regexr.com/3qveu了解测试。你知道吗
相关问题 更多 >
编程相关推荐