python:多行正则表达式
我有一段文字,需要从中提取出用户名和哈希值。目前我是用两个正则表达式来完成这个任务。请问我能不能用一个多行的正则表达式来实现呢?
#!/usr/bin/env python
import re
test_str = """
Hello, UserName.
Please read this looooooooooooooooong text. hash
Now, write down this hash: fdaf9399jef9qw0j.
Then keep reading this loooooooooong text.
Hello, UserName2.
Please read this looooooooooooooooong text. hash
Now, write down this hash: gtwnhton340gjr2g.
Then keep reading this loooooooooong text.
"""
logins = re.findall('Hello, (?P<login>.+).',test_str)
hashes = re.findall('hash: (?P<hash>.+).',test_str)
3 个回答
2
这是一个简单的pyparsing
版本:
from pyparsing import *
username = Word(alphas,alphanums+"_")
hash = Word(alphanums)
patt = ("Hello," + username("username") + '.' +
SkipTo("write down this hash:", include=True) +
hash("hash"))
for tokens,start,end in patt.scanString(test_str):
print tokens.hash, '->', tokens.username
# or to build a dict
hashNameLookup = dict((t.hash, t.username)
for t,s,e in patt.scanString(test_str))
输出结果是:
fdaf9399jef9qw0j -> UserName
gtwnhton340gjr2g -> UserName2
2
这段内容是关于编程的讨论,主要涉及一些技术细节和解决方案。它可能包含了代码示例和一些常见问题的解答。对于初学者来说,理解这些内容可能需要一些基础知识,但我会尽量用简单的语言来解释。
首先,代码块
name_hash_pair = re.findall('Hello, ([^.]+).*?hash: ([^.]+)', test_str, re.DOTALL)
#gives [('UserName', 'fdaf9399jef9qw0j'), ('UserName2', 'gtwnhton340gjr2g')]
可能包含了一些示例代码,这些代码是用来展示如何解决特定问题的。通常,代码是由一系列指令组成,计算机通过这些指令来执行任务。
在编程中,大家常常会遇到各种各样的问题,比如如何让程序运行得更快,或者如何修复错误。讨论中提到的解决方案可能会涉及到一些编程技巧,比如优化代码、使用不同的算法,或者调整程序的结构。
总之,这段内容的核心是帮助大家理解如何在编程中解决问题,提升自己的技能。即使你是初学者,也可以通过不断学习和实践,逐渐掌握这些知识。
5
试试这个:
re.findall(r'Hello, (?P<login>[^.]+)\..+?hash: (?P<hash>[^.]+)', test_str, re.S)