Regex in Swift


現況

Swift 中並沒有內建Regex的Class, Struct或Type。未來"可能"會有。

本文以Swift1.2, Xcode 6.3為準

解決方案

1.用NSRegularExpression包成Class, Struct, Function

String要轉成NSString

教學

擴充

  • SwiftRegex Perl-like regex =~ operator for Swift

  • SwiftRegex Some regular expression operators for Swift

  • ExSwift A set of Swift extensions for standard types and classes.

  • Objective-C-RegEx-Categories NSRegularExpression extensions that make regular expressions easier in Objective-C, Swift, iOS, OSX

2.呼叫Foundation中方法rangeOfString:options:帶有RegularExpressionSearch選項。這是Swift的語法

妙的是這個NSStringCompareOptions可以用.RegularExpressionSearch的enum值,代表傳入aString的會是個Regex。

func rangeOfString(_ aString: String!,options mask: NSStringCompareOptions) -> NSRange
let myStringToBeMatched = "ThisIsMyString"
let myRegex = "ing$"
if let match = myStringToBeMatched.rangeOfString(myRegex, options: .RegularExpressionSearch){
    println("\(myStringToBeMatched) is matching!")
}

參考