PowerShell中截取字符串数组内第一个短横线前的内容
提取字符串中第一个短横线前的内容
给定待处理的字符串数组:
Cola-12-0-15-300-122 Pepsi-123-34-543 7_Up-rrr-12-2342-2 Fanta_Mineral-1212-fgdfg-33
目标是提取每个字符串里第一个短横线(-)之前的内容,同时将7_Up转为7_up,最终得到如下结果:
Cola Pepsi 7_up Fanta_Mineral
方法一:Python 实现
通过字符串分割和简单替换处理即可完成需求:
# 原始字符串列表 raw_strings = [ "Cola-12-0-15-300-122", "Pepsi-123-34-543", "7_Up-rrr-12-2342-2", "Fanta_Mineral-1212-fgdfg-33" ] processed = [] for s in raw_strings: # 按短横线分割,取第一个片段 first_part = s.split('-')[0] # 单独处理7_Up的大小写问题 if first_part == "7_Up": first_part = "7_up" processed.append(first_part) # 打印结果 for item in processed: print(item)
方法二:Shell 命令实现
如果是处理文件中的内容,可结合awk和sed快速完成:
# 假设内容保存在input.txt中 awk -F '-' '{print $1}' input.txt | sed 's/7_Up/7_up/'
运行上述任一方案,都能得到预期的输出结果。
内容的提问来源于stack exchange,提问作者Sergio Ramos
相关产品推荐
相关产品推荐

