更新时间:2023-11-26 12:21:40
下面的第一个代码表现出不稳定的行为,你不应该使用它.(请参阅本答案的后半部分.)
The first code below have shown unstable behaviour and you should not use it. (Please see the latter part of this answer.)
在可失败的初始化程序中添加一行:
Add one line to your failable initializer:
do {
try self.init(pattern: pattern, options: regexOption)
} catch {
print(error)
return nil //->you need to return nil to tell initialization failed
}
(我认为 Swift 编译器应该警告这个缺失的 return nil
.可能是 Swift 的一个错误?)
(I think Swift compiler should warn about this missing return nil
. May be a bug of Swift?)
之后,您可以安全地检查结果是否为零:
After that you can safely check the result if it's nil or not:
let sOpts = SearchOptions(searchString: "\\", replacementString: "", matchCase: false, wholeWords: false)
if let regex = NSRegularExpression(options: sOpts) {
//Use regex
print(regex)
} else {
//Process errors
print("Something bad in SearchOptions")
}
(我省略了 escapeMetacharacters
,因为它还没有使用.)
(I omitted escapeMetacharacters
, as it's not used yet.)
据我测试,使用静态方法从未崩溃过.
As far as I tested, using static method has never crashed.
extension NSRegularExpression {
static func expresssionWith(options: SearchOptions) -> NSRegularExpression? {
let searchString = options.searchString
let isCaseSensitive = options.matchCase // set to true
let isWholeWords = options.wholeWords // set to false
// handle case sensitive option
var regexOption: NSRegularExpressionOptions = .CaseInsensitive
if isCaseSensitive { // if it is match case remove case sensitive option
regexOption = []
}
// put the search string in the pattern
var pattern = searchString
if isWholeWords {
pattern = "(?<!\\w)" + NSRegularExpression.escapedPatternForString(searchString) + "(?!\\w)"
}
do {
return try NSRegularExpression(pattern: pattern, options: regexOption)
} catch {
print(error)
return nil
}
}
}
let sOpts = SearchOptions(searchString: "\\", replacementString: "", matchCase: false, wholeWords: false)
if let regex = NSRegularExpression.expresssionWith(sOpts) {
//Use regex
print(regex)
} else {
//Process errors
print("Something bad in SearchOptions")
}