簡體   English   中英

在python中使用正則表達式在字符串中查找多個事物

[英]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的更多信息

re.findall的文檔

希望這可以幫助!

如果您喜歡DIY,請考慮創建一個tokenizer 這是非常優雅的“ python方式”解決方案。

或使用標准庫: https ://docs.python.org/3/library/urllib.parse.html,但請注意,您的示例URL並非完全有效:沒有模式'conn_type'並且您有兩個錨點查詢字符串,因此urlparse無法正常工作。 但是對於現實生活中的URL,我強烈建議使用這種方法。

>>>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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM