Search code examples
swiftmatchsql-likestring-comparison

SQL like & matches query on string in Swift


I want to write a function that can perform comparison with two strings.

Something like this:

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

I want to support the following types in the StringComparisonOperator

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

Swift provides ==(for equals), .contains(for contains), .hasPrefix(for beginsWith) and .hasSuffix(for endsWith).

But, I don't have any idea about like and matches options. Can someone help me in this?


Solution

  • You can create an infix operator for like and matches

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

    and use like: "abcd" =~ "ab*cd"