python - 正则表达式不会从日志文件中提取整个 ID?

标签 python regex

我在日志文件中有以下输入,我有兴趣捕获 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

如果能帮助我编辑正则表达式,我将不胜感激。

最佳答案

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

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

关于python - 正则表达式不会从日志文件中提取整个 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36290371/

相关文章:

python - 从 PLY 向解析器的调用者报告解析错误

像excel一样的Python字符串序列

regex - Perl6 搜索然后替换为子程序的输出

javascript - 正则表达式 : matching specific character within a context

python - Time.sleep() 函数放置

python - 计划任务 : how to run a script that requires to open display?

python - Pandas 将两列相加,跳过 NaN

Java 正则表达式仅匹配单词('、-、空格)

php - RegEx - 如何在文件扩展名前插入字符串

python - 正则表达式查找从行尾开始的第一个匹配项