使用Python提取符合模式的子字符串,代码量较少

2024-06-25 06:12:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python字符串结尾用换行符分隔:

mystring = "owner: uid=rocdsc,ou=People,dc=fcd,dc=test,dc=com
member: uid=absylor12,ou=people,dc=fcd,dc=test,dc=com
member: uid=amslsmith,ou=people,dc=fcd,dc=test,dc=com
member: uid=amis,ou=people,dc=fcd,dc=test,dc=com
member: uid=null,ou=people,dc=fcd,dc=test,dc=com""

有没有更好的方法来生成uid数组,只需如下所示:

[rocdsc, absylor12, amslsmith, amis]

没有

null

在数组列表中。你知道吗

我试过:

uids= [name.strip() for name in mystring .split("\n")]        

    if len(uids)>0:
        for index in range(len(uids))
            #print 'Current UIDs:', uids[index].split(":")
            uids[0] = uids[0].split("=")[1].strip()
    print uids

Tags: testcomuidoudcpeoplemembersplit
2条回答
#!python2

import re

mystring = "owner: uid=rocdsc,ou=People,dc=fcd,dc=test,dc=com, member: uid=absylor12,ou=people,dc=fcd,dc=test,dc=com, member: uid=amslsmith,ou=people,dc=fcd,dc=test,dc=com, member: uid=amis,ou=people,dc=fcd,dc=test,dc=com, member:, uid=null,ou=people,dc=fcd,dc=test,dc=com"

# pattern definition
p = 'uid='

# holds user names
users = []

# split string on a space or a comma, find user id, append to list
for item in re.split(' |,|', mystring):
    if item.startswith(p):
        users.append(item.replace(p, ''))

print users

如果您没有尝试过正则表达式:

import re
r = re.compile(r'uid=(\w+)')
r.findall(mystring)

如果您想删除空值,可以filter(lambda x: x != 'null', r.findall(mystring))(再迭代一次)

这个正则表达式可以工作,但也会删除所有以null开头的uid

re.compile(r'uid=((?!null)\w+)').findall(mystring)

相关问题 更多 >