Swift中如何删除字符串特定模式并转换为步骤数组?
在Swift中去除步骤编号并生成步骤数组的解决方案
方法一:分割字符串后逐个清理前缀
逻辑直观,适合新手理解:
- 先移除字符串开头的多余换行
- 按换行符分割成带编号的步骤数组
- 用正则批量去除每个步骤的编号前缀
let input = "\n\n1. Separate clothes into whites, lights and darks.\n2. Fill washing machine with cold water and select the appropriate cycle for the type of clothing.\n3. Add the appropriate laundry detergent, fabric softener and other laundry additives.\n4. Place clothes in the washing machine and press start." // 移除开头的换行符 let trimmedInput = input.trimmingCharacters(in: .newlines) // 按换行分割成带编号的步骤数组 let numberedSteps = trimmedInput.components(separatedBy: .newlines) // 清理每个步骤的编号前缀 let cleanedSteps = numberedSteps.map { step in step.replacingOccurrences(of: #"^\d+\.\s"#, with: "", options: .regularExpression) } // 输出目标数组:["Separate clothes into whites, lights and darks.", ...] print(cleanedSteps)
正则说明
#"^\d+\.\s"# 是Swift的原始字符串(避免反斜杠转义),含义:
^:匹配行首\d+:匹配一个或多个数字\.:匹配点号(需转义,因为点号在正则中是通配符)\s:匹配空格
方法二:直接用正则提取所有步骤内容
一步到位,通过正则捕获并提取每个步骤的核心文本:
let input = "\n\n1. Separate clothes into whites, lights and darks.\n2. Fill washing machine with cold water and select the appropriate cycle for the type of clothing.\n3. Add the appropriate laundry detergent, fabric softener and other laundry additives.\n4. Place clothes in the washing machine and press start." do { // 正则匹配行首的编号+点+空格,捕获后面的步骤文本 let regex = try NSRegularExpression(pattern: #"^\d+\.\s(.+)$"#, options: .anchorsMatchLines) let fullRange = NSRange(input.startIndex..., in: input) let matches = regex.matches(in: input, range: fullRange) let cleanedSteps = matches.compactMap { match in // 提取捕获组的内容(即步骤文本) guard let stepRange = Range(match.range(at: 1), in: input) else { return nil } return String(input[stepRange]) } print(cleanedSteps) } catch { print("正则表达式错误:\(error)") }
关键参数说明
.anchorsMatchLines:让正则中的^和$匹配每一行的开头和结尾,而非整个字符串的首尾match.range(at: 1):提取正则中第一个捕获组(括号内的内容),也就是步骤的核心文本
为什么你的Python正则在Swift中不生效?
Swift的正则基于ICU标准,和Python的re模块存在语法差异:
- 转义处理:Swift普通字符串中反斜杠需要写两次(如
"^\\d+\\.\\s"),建议用原始字符串#"..."#简化 - 你的原正则中
(?=.\d|\d)这类前瞻断言完全没必要——当前场景只需匹配行首的数字.前缀,不需要复杂的数字匹配逻辑 - Swift中调用正则的方式和Python不同,要么用
String.replacingOccurrences便捷调用,要么通过NSRegularExpression创建实例
内容的提问来源于stack exchange,提问作者Kian Malakooti
相关产品推荐
相关产品推荐

