SQL喜欢并在Swift中匹配字符串查询

问题描述 投票:0回答:1

我想编写一个可以与两个字符串进行比较的函数。

类似这样的东西:

func stringComparison(_ str1:String, comparisonOperator:StringComparisonOperator, _ str2:String)
{
   ...
}

我想在StringComparisonOperator中支持以下类型

enum StringComparisonOperator {
    case equals
    case contains
    case beginsWith
    case endsWith
    case like
    case matches
}

[Swift提供==(用于等于),.contains(用于包含),.hasPrefix(用于BeginsWith)和.hasSuffix(用于endsWith)。

但是,我对likematches选项一无所知。有人可以帮我吗?

swift match sql-like string-comparison
1个回答
1
投票

您可以为likematches创建一个中缀运算符

infix operator =~
func =~ (string: String, regex: String) -> Bool {
    return string.range(of: regex, options: .regularExpression) != nil
}

并且使用类似:"abcd" =~ "ab*cd"

© www.soinside.com 2019 - 2024. All rights reserved.