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

如何在Swift的switch case语句中使用正则字面量表达式?

Swift 5.7正则特性在switch case中的正确用法

问题重现

按照WWDC 2022演示示例编写的代码无法编译,原代码如下:

import Foundation
import RegexBuilder

switch "abc" {
    case /\w+/.wholeMatch:
        print("matched!")
    default:
        print("not matched.")
}

编译时报错:

Expression pattern of type Regex<Substring> cannot match values of type String

原因分析

默认的正则字面量/\w+/会生成Regex<Substring>类型的实例,但switch的匹配目标是String类型,两者类型不兼容,导致无法匹配。

解决方案

这里提供三种可行的修改方式:

方式一:将匹配目标转为Substring

把switch的字符串参数转为Substring类型,让其与正则的类型匹配:

import Foundation
import RegexBuilder

switch "abc"[...] {
    case /\w+/.wholeMatch:
        print("matched!")
    default:
        print("not matched.")
}

方式二:使用where子句结合wholeMatch(of:)

通过where条件判断字符串是否匹配正则,无需修改目标类型:

import Foundation
import RegexBuilder

switch "abc" {
    case let str where str.wholeMatch(of: /\w+/) != nil:
        print("matched!")
    default:
        print("not matched.")
}

方式三:显式指定正则为String类型

直接创建匹配String类型的正则实例,让其与目标类型一致:

import Foundation
import RegexBuilder

switch "abc" {
    case Regex<String>(/\w+/).wholeMatch:
        print("matched!")
    default:
        print("not matched.")
}

使用要点

  • 正则字面量默认生成Regex<Substring>,若匹配目标是String,需做类型适配
  • 若只需部分匹配,可直接在case中使用正则字面量:
switch "abc123" {
    case /\w+\d+/:
        print("包含字母和数字的字符串")
    default:
        print("不匹配")
}
  • 若需要完全匹配,则必须结合.wholeMatch或者在正则首尾添加^和$锚点。

内容的提问来源于stack exchange,提问作者marc-medley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:05:15