Power Query M代码问题:首字符为大写/数字时未返回指定|符号
Power Query M代码修正:首字符为大写字母/数字时返回
|符号 需求与问题
- 需求:当源数据行的首字符为大写字母或数字时,返回符号
|;否则返回空格。 - 当前问题:原有M代码仅对大写字母开头的行生效,数字开头的行(如「2.0. SUBHEADING」)无法正确返回目标符号。
- 要求:直接在代码中指定匹配字符列表,无需额外查询操作。
原有M代码
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"Merged", type text}}), #"Added Custom4" = Table.AddColumn(#"Changed Type", "Custom.2", each if List.Count(Splitter.SplitTextByAnyDelimiter( {"a".."z","0".."9"} ) (Text.Start([Merged], 1))) > 1 then " " else "| ") in #"Added Custom4"
问题原因
原有代码逻辑颠倒:用小写字母和数字作为分隔符拆分首字符,若首字符是数字,拆分后列表长度大于1,因此返回空格而非|,仅大写字母开头的行能触发正确返回。
修正后的M代码
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"Merged", type text}}), #"Added Custom" = Table.AddColumn(#"Changed Type", "Custom.2", each let firstChar = Text.Start([Merged], 1), targetChars = List.Combine({{"0".."9"}, {"A".."Z"}}) in if List.Contains(targetChars, firstChar) then "| " else " ") in #"Added Custom"
代码说明
- 直接定义目标匹配集合:
List.Combine({{"0".."9"}, {"A".."Z"}})包含所有数字(0-9)和大写字母(A-Z)。 - 提取每行首字符:
Text.Start([Merged], 1)。 - 判断首字符是否在目标集合中:
List.Contains(targetChars, firstChar),符合条件返回|,否则返回空格。
数据示例
SUBHEADING 1 Non-sensical sentence 1. Sentence 2. Sentence 3 part 3a, part 3b, and part 3c. SUBHEADING 1.1. Non-sensical sentence 4. Sentence 5. Sentence 6 part 3a, part 3b, 3c and 3d. 2.0. SUBHEADING Extra Info 1 (Not a proper sentence) Extra Info 2 Sentence 7. SUBHEADING 3.0 Sentence 8.
修正后,以下行将正确返回| :
- SUBHEADING 1
- SUBHEADING 1.1.
- 2.0. SUBHEADING
- SUBHEADING 3.0
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

