Dear Erica: How do I perform regular expression search in Swift strings?

Depends on Foundation. I don’t love it but here you go.

"Hello".rangeOfString("l{2}", 
    options: [.RegularExpressionSearch], 
    range: "Hello".startIndex..<"Hello".endIndex, 
    locale: nil)

infix operator ~== {}
func ~==(lhs: String, rhs: String) -> Range<String.Index>? {
    return lhs.rangeOfString(rhs, 
        options: [.RegularExpressionSearch], 
        range: lhs.startIndex..<lhs.endIndex, 
        locale: nil)
}

"Hello" ~== "l{2}" // 2..<4

Thanks, Quark67 for catching typo

3 Comments

  • I spent too much time trying to figure out “1{2}” until I realized it was the letter L, not the number 1. 😉

  • On my Xcode 6.4, I must remove [ ] around .RegularExpressionSearch, else I have this error: ‘AnyObject.Protocol’ does not have a member named ‘RegularExpressionSearch’.

    Also, it seems that:
    range: lhs.startIndex..<rhs.endIndex
    must be replaced by:
    range: lhs.startIndex..<lhs.endIndex

    (rhs replaced by lhs)

    If not, "Heelloo" ~== "l{2}" return nil.

    I'm beginner, so perhaps I'm wrong? (I test with playground).

  • Just change “Hello” to “Happy” and “l{2}” to “p{2}”. This is too hard to read.

    Also: readable function names are massively better than custom operators. Twiddle Equals Equals?