You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取字符串列表中各元素首次出现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:55:11