[英]python find all matches of multiple strings in a given string using regex?
[英]find multiple things in a string using regex in python
我的输入字符串包含各种不同的实体,例如: conn_type:// host:port / schema#login#password
我想找出所有使用python中的正则表达式的人。
截至目前,我能够一一找到它们,例如
conn_type=re.search(r'[a-zA-Z]+',test_string)
if (conn_type):
print "conn_type:", conn_type.group()
next_substr_len = conn_type.end()
host=re.search(r'[^:/]+',test_string[next_substr_len:])
等等。
有没有if if else的方法 ? 我希望有某种方法,但无法找到它。 请注意,每个实体正则表达式都是不同的。
请帮忙,我不想写一个无聊的代码。
您为什么不使用re.findall?
这是一个例子:
import re;
s = 'conn_type://host:port/schema#login#password asldasldasldasdasdwawwda conn_type://host:port/schema#login#email';
def get_all_matches(s):
matches = re.findall('[a-zA-Z]+_[a-zA-Z]+:\/+[a-zA-Z]+:+[a-zA-Z]+\/+[a-zA-Z]+#+[a-zA-Z]+#[a-zA-Z]+',s);
return matches;
print get_all_matches(s);
这将返回一个与当前正则表达式完全匹配的列表,如本例所示,在本例中为:
['conn_type://host:port/schema#login#password', 'conn_type://host:port/schema#login#email']
如果您需要使用Python创建正则表达式模式的帮助,建议您使用以下网站:
另请参阅re模块的文档以获取有关re.findall的更多信息
希望这可以帮助!
>>>import re
>>>uri = "conn_type://host:port/schema#login#password"
>>>res = re.findall(r'(\w+)://(.*?):([A-z0-9]+)/(\w+)#(\w+)#(\w+)', uri)
>>>res
[('conn_type', 'host', 'port', 'schema', 'login', 'password')]
无需ifs。 使用findall或finditer搜索您的连接类型集合。 根据需要过滤元组列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.