简体   繁体   中英

Python replacing regex group

I am using Python version 2.7.6

I have an expression which indicates a ftp uri;

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

Assume that, I have a matched string to the pattern which is;

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

What I want is to add username and password to that uri according to regex group position. I wish there could be a way like ;

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:my_password@somehost:21/blah_blah_path.file"

I searched it and could find some replacement with regex. But they were replacing out of a group parts in regex. I actually want to replace or set a group value in a string matched a regex.

Do you know a way to replace some match group value in a string with regex?

I do not think it is possible, because capturing is used to obtain the information we want. Instead, I'd use the regex to check the format of the string, and re-build the output in order to obtain the required string using existing dictionary with new data.

Here is an example of this approach:

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:pass@somehost: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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM