牛骨文教育服务平台(让学习变的简单)
博文笔记

python学习笔记-正则表达式提取指定关键字

创建时间:2016-07-13 投稿人: 浏览次数:7619

背景

提取一个字符串中“hash=”之后连续的字符。

方法1:

通过对string的操作,获取“hash=”之后长度为32的子字符串。

# -*- coding: utf-8 -*-
__author__ = "jason"
#从日志文件中提取出hash=
import re
fp = open("testdata.txt", "r")
while 1:
    line = fp.readline()
    if not line:
        break
    index = line.find("hash=")
    index = index + len("hash=")
    print(line[index:index+32])

方法2:

通过正则匹配的方式,匹配出“hash=”之后的的子字符。

# -*- coding: utf-8 -*-
__author__ = "jason"
#从日志文件中提取出hash=
import re
fp = open("testdata.txt", "r")
while 1:
    line = fp.readline()
    if not line:
        break
    s = re.findall(r"hash=(w+)*", line, re.M)
    print s[0]
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。