python学习笔记-正则表达式提取指定关键字
背景
提取一个字符串中“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]
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: python-用正则表达式筛选文本信息
- 下一篇: python解析json串与正则匹配对比