gpt4 book ai didi

python - 在 python 中使用正则表达式在字符串中查找多个内容

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:56 26 4
gpt4 key购买 nike

我的输入字符串包含如下各种实体: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 和 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 制作正则表达式模式方面需要帮助,我建议您使用以下网站:

A pretty neat online regex tester

另请查看 re 模块的文档以获取有关 re.findall 的更多信息

Documentation for re.findall

希望这对您有所帮助!

关于python - 在 python 中使用正则表达式在字符串中查找多个内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41995198/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com