Extract substrings that follow a pattern in Python with less code

Milson Source

My python string is with separated by \n newline at the end:

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

Is there a better way to generate an array of uid's only as follows:

[rocdsc, absylor12, amslsmith, amis]



in the array list.

I tried:

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


answered 1 week ago Lorenzo Peña #1

If you haven't tried regular expressions:

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

If you want to remove the null you can filter(lambda x: x != 'null', r.findall(mystring)) (one more iteration)

And this regular expression works, but will also remove all uids starting with the word null


answered 1 week ago Michael Swartz #2


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

comments powered by Disqus