如何提取字符串列表中各元素首次出现CN=后的对应子串?
提取LDAP字符串中首次
CN=后的内容 你的原始数据:
ls = ['CN=text_1 ,CN =Users,OU=text_12,DC=eample,DC=com', 'CN=text_3433,CN=users,OU=text4,DC=example,DC=com']
预期结果:
ls_f = ['text_1','text_3433']
方法一:纯字符串操作
利用find定位关键位置,再切片处理,还能自动处理CN=后可能带的空格:
ls_f = [s[s.find('CN=')+3:s.find(',', s.find('CN=')+3)].strip() for s in ls]
拆解步骤看更清晰:
ls_f = [] for s in ls: # 找到"CN="的结束索引 cn_end_idx = s.find('CN=') + 3 # 从该位置开始找第一个逗号的索引 comma_idx = s.find(',', cn_end_idx) # 截取子串并去除首尾空白(比如第一个字符串里text_1后面的空格) target_str = s[cn_end_idx:comma_idx].strip() ls_f.append(target_str)
方法二:正则表达式(更适配复杂格式)
如果字符串格式可能有变化(比如逗号前空格可有可无),用正则更稳妥:
import re # 匹配开头的CN=,然后捕获直到第一个(空格+逗号)的内容 pattern = re.compile(r'^CN=(.*?)\s*,') ls_f = [pattern.search(s).group(1) for s in ls]
如果存在字符串末尾没有逗号的情况,可调整正则兼容:
pattern = re.compile(r'^CN=(.*?)(?:\s*,|$)') ls_f = [pattern.search(s).group(1).strip() for s in ls]
内容的提问来源于stack exchange,提问作者pythondumb
相关产品推荐
相关产品推荐

