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

Power Query 如何删除字符串首个小写字母及其后的所有文本

问题描述

数据表中单元格内容示例:

PRO-PLAS AFRICA EXPOPlastic Machinery & Materials Exhibition. PRO-PLAS AFRICA EXPO features Plastics processing machinery, Chillers, Converting equipment, Extrusion equipment, Feeders, Processing aids, Recycling equipment, Various materials, Blow moulding machinery

转换规则:

  • 第一步:从字符串内第一个小写字母的位置开始,删除该位置及之后所有内容,示例处理后得到PRO-PLAS AFRICA EXPOP
  • 第二步:删除上一步结果的最后一个字母,最终得到目标值PRO-PLAS AFRICA EXPO

注意:每个单元格中首个小写字母的出现位置不固定,无法用固定长度截取。

已尝试方案的问题

按空格拆分逐词判断全大写

使用代码:

#"Added Custom" = Table.AddColumn(#"Changed Type", "allCaps", each 
        Text.Combine(
            List.Accumulate(Text.Split([Column1]," "),
                            {},
                            (state, current)=>  
                                if List.ContainsAny(
                                        Text.ToList(current),
                                            {"0".."9","a".."z",",",":","?","/","\"," "}) 
                                then state 
                                else state & {current}),", "))

运行结果:PRO-PLAS AFRICA & PRO-PLAS AFRICA EXPO
问题原因:首个小写字母出现在单词EXPOPlastic内部,该词同时包含大小写字母,整词判断的逻辑会直接跳过该词,错误保留了后续的全大写内容。

直接删除所有小写字母

使用Text.Remove删除所有小写字母后得到结果:

PRO-PLAS AFRICA EXPOP M & M E. PRO-PLAS AFRICA EXPO P, C, C, E, F, P, R V , B
问题原因:仅删除小写字符,第一个小写字母之后的大写字母、标点符号都会被保留,不符合截断要求。

可行实现方案

直接定位第一个小写字母的字符位置做截断即可,不需要按空格拆分单词,适配任意位置出现小写字母的场景,M代码如下:

#"Added Custom" = Table.AddColumn(#"Changed Type", "allCaps", each 
  let
    // 定位第一个小写字母的索引位置
    firstLowerIndex = List.PositionOfAny(Text.ToList([Column1]), {"a".."z"}),
    // 第一步:截取到第一个小写字母之前的内容
    step1 = Text.Start([Column1], firstLowerIndex),
    // 第二步:去掉结果最后1位
    result = Text.Start(step1, Text.Length(step1) - 1)
  in
    result
)

如果需要兼容无小写字母的极端场景(比如整段全大写),可以加边界判断避免报错:

#"Added Custom" = Table.AddColumn(#"Changed Type", "allCaps", each 
  let
    firstLowerIndex = List.PositionOfAny(Text.ToList([Column1]), {"a".."z"}),
    step1 = if firstLowerIndex = -1 then [Column1] else Text.Start([Column1], firstLowerIndex),
    result = if Text.Length(step1) > 0 then Text.Start(step1, Text.Length(step1) - 1) else step1
  in
    result
)

内容的提问来源于stack exchange,提问作者Alastair

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:15:51