![](/img/trans.png)
[英]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.