如果正则表达式有效,如何检查 Swift? [英] How to check in Swift if a Regular Expression is valid?

查看:26
本文介绍了如果正则表达式有效,如何检查 Swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式在 textView 中进行搜索.对于简单的字符串,一切正常,但是当我尝试仅输入正则表达式运算符的一部分时,我收到了错误提示:

I'm using Regex to search in a textView. All works fine with simple strings but when I try to enter only a part of a regular expression operator I get a cash with the error:

Error Domain=NSCocoaErrorDomain Code=2048 "The value "\" is invalid." UserInfo={NSInvalidValue=\}

例如,如果我输入\n"它可以工作,但如果我只输入\"(不带引号),我就会崩溃.我做不到的是想办法在使用之前检查表达式.

For example if I enter "\n" it works, but if I enter only "\" (without quotes), I get the crash. What I can't get to do is to find a way to check the expression before to use it.

我使用此代码的部分依据是本教程这个答案来自Wiktor Stribiżew:

I'm using this code partially based on this tutorial and this answer by Wiktor Stribiżew:

extension NSRegularExpression {
    convenience init?(options: SearchOptions) {
        let searchString = options.searchString
        let isCaseSensitive = options.matchCase // set to true
        let isWholeWords = options.wholeWords // set to false
        let escapeMetacharacters = options.escapeMetacharacters // 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 {
            try self.init(pattern: pattern, options: regexOption)
        } catch {
            print(error)
        }
    }
}

推荐答案

下面的第一个代码表现出不稳定的行为,你不应该使用它.(请参阅本答案的后半部分.)

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")
}

这篇关于如果正则表达式有效,如何检查 Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆