正则表达式不会从日志文件中提取整个id吗?

2024-04-25 21:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在日志文件中有以下输入,我想捕获ID的所有部分,但是它不会返回整个ID,只返回其中的一部分:

id:A2uhasan30hamwix١٦٠٢٢٧١٣٣٣١١٣٥٤ 
id:A2uhasan30hamwix160212145302428 
id:A2uhasan30hamwix١٦٠٢٠٩١٣٠١٥٠٠١١ 
id:A2uhasan30hamwix١٦٠٢٠٩١٦٤٧٣٩٧٣٢ 
id:A2uhasan30hamwix١٦٠٢٠٨١٩٢٨٠١٩٠٧ 
id:A2uhasan30hamwix160207145023750

我在python 2.7中使用了以下正则表达式:

I have edited sid to id:
RE_SID = re.compile(r'sid:(<<")?(?P<sid>([A-Za-z0-9._+]*))', re.U)

>>> RE_SID = re.compile(ur'id:(<<")?(?P<sid>[A-Za-z\d._+]*)', re.U)
>>> sid = RE_SID.search('id:A2uhasan30hamwix١٦٠٢٢٧١٣٣٣١١٣٥٤').group('sid')
>>> sid
'A2uhasan30hamwix'

我的结果是:

is: A2uhasan30hamwix

编辑后: 以下是我读取日志文件的方式:

with open(cfg.log_file) as input_file: ...
     fields = line.strip().split(' ')

日志中的行示例:

2015-11-30T23:58:13.760950+00:00 calxxx enexxxxce[10476]: INFO consume_essor: user:<<"ailxxxied">> callee_num:<<"+144442567413">> id:<<"A2uhasan30hamwix١٦٠٢٠٨١٩٢٨٠١٩٠٧">> credits:0.0 result:ok provider:sipovvvv1.yv.vs

我会很感激帮助我编辑我的正则表达式。你知道吗


Tags: 文件reid编辑havefilecompilesid
3条回答
string = '''
id:A2uhasan30hamwix١٦٠٢٢٧١٣٣٣١١٣٥٤ 
id:A2uhasan30hamwix160212145302428 
id:A2uhasan30hamwix١٦٠٢٠٩١٣٠١٥٠٠١١ 
id:A2uhasan30hamwix١٦٠٢٠٩١٦٤٧٣٩٧٣٢ 
id:A2uhasan30hamwix١٦٠٢٠٨١٩٢٨٠١٩٠٧ 
id:A2uhasan30hamwix160207145023750
'''
import re
reObj = re.compile(r'id:.*')
ans = reObj.findall(string,re.DOTALL)

print(ans)

输出:

['id:A2uhasan30hamwix160212145302428 ', 
 'id:A2uhasan30hamwix١٦٠٢٠٩١٣٠١٥٠٠١١ ', 
 'id:A2uhasan30hamwix١٦٠٢٠٩١٦٤٧٣٩٧٣٢ ', 
 'id:A2uhasan30hamwix١٦٠٢٠٨١٩٢٨٠١٩٠٧ ', 
 'id:A2uhasan30hamwix160207145023750']

要解决的三件事:

固定版本:

id:(<<")?(?P<sid>[A-Za-z\d_.+]+)

根据我们在聊天中讨论的内容,发布解决方案:

import codecs
import re
RE_SID = re.compile(ur'id:(<<")?(?P<sid>[A-Za-z\d._+]*)', re.U) # \d used to match non-ASCII digits, too
input_file = codecs.open(cfg.log_file, encoding='utf-8')  # Read the file with UTF8 encoding
for line in input_file: 
    fields = line.strip().split(u' ') # u prefix is important!
    if len(fields) >= 11: 
    try: 
        # ...... 
        sid = RE_SID.search(fields[7]).group('sid') # Or check if there is a match first

相关问题 更多 >

    热门问题