2015-03-02 131 views
0

我使用Python version 2.7.6Python的替換正則表達式組

我有其指示一個ftp URI的表達;

pattern = re.compile(r'ftp://((?P<username>[^:.]+):(?P<password>[^@.]+)@)?(?P<host>[^:.]+):(?P<port>[^/.]+)(?P<path>.+)') 

假設,我有一個匹配的字符串模式,它是;

my_ftp_uri="ftp://somehost:21/blah_blah_path.file" 

我要的是根據正則表達式組位置,用戶名和密碼添加到URI。 我希望可以有這樣一種方式,如;

match=pattern.search(my_ftp_uri) 
match.groupdict() 
>>> {'username': None, 'path': '/blah_blah_path.file', 'host': 'somehost', 'password': None, 'port': '21'} 

match.group_replace({'username':'my_username','password':'my_password'}) 
>>> "ftp://my_username:[email protected]:21/blah_blah_path.file" 

我搜索了它,可以找到一些正則表達式替換。但他們正在用正則表達式替換組中的部分。我實際上想要替換或設置匹配正則表達式的字符串中的組值。

你知道一種用正則表達式替換字符串中某個匹配組值的方法嗎?

+0

你不得不使用正則表達式?否則,你可以使用python的[urlparse](https://docs.python.org/2/library/urlparse.html)。 – Tommy 2015-03-02 09:54:57

回答

0

我不認爲這是可能的,因爲捕獲是用來獲取我們想要的信息。相反,我會使用正則表達式來檢查字符串的格式,並重新構建輸出以便使用現有字典和新數據獲取所需的字符串。

下面是這種方法的一個例子:

host = ["YOUR.COM", "YOUR.COM2", "YOUR.COM3"] 
password = ["PASS4", "PASS5", "PASS6"] 
user = ["USER2", "USER3", "USER4"] 
port = ["345", "355", "365"] 
path = ["/GO.to.page11","/GO.to.page22","/GO.to.page33"] 
p = re.compile(ur'ftp:\/\/(?:(?P<username>[^.:]+):(?P<password>[^@.]+)@)?(?P<host>[^:.]+):(?P<port>[^\/.]+)(?P<path>.+)', re.MULTILINE) 
test_str = u"my_ftp_uri=\"ftp://somehost:21/blah_blah_path.file\"" 
test_str2 = u"my_ftp_uri=\"ftp://username:[email protected]:21/blah_blah_path.file\"" 

matchObj = p.search(test_str)     # Test 1 
if matchObj and matchObj.group(1) != None: 
    for i, entry in enumerate(host): 
     print p.sub(ur"ftp://" + user[i] + ":" + password[i] + "@" + host[i] + ":" + port[i] + path[i], test_str) 
else: 
    for i, entry in enumerate(host): 
     print p.sub(ur"ftp://" + host[i] + ":" + port[i] + path[i], test_str) 

matchObj2 = p.search(test_str2)     # Test 2 
if matchObj2 and matchObj2.group(1) != None: 
    for i, entry in enumerate(host): 
     print p.sub(ur"ftp://" + user[i] + ":" + password[i] + "@" + host[i] + ":" + port[i] + path[i], test_str2) 
else: 
    for i, entry in enumerate(host): 
     print p.sub(ur"ftp://" + host[i] + ":" + port[i] + path[i], test_str2)