本文介绍了在Swift中使用Regex进行简单搜索时,如何避免因搜索字符串中的特殊字符而导致的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Regex在textView中搜索单词。我实现了textField和两个switch作为选项(整个单词和匹配大小写)。当您在搜索字段中输入普通单词时,所有工作都正常,但是当我输入特殊字符(如\或*)时出现错误。

I'm using Regex to search for a word in a textView. I implemented a textField and two switch as options (Whole words and Match case). All work fine when you enter a plain word in the search filed but I get an error when I enter a special character like \ or *.

我得到的错误就像这样:

The error I get is like this one:

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

有没有办法避免这个问题并让代码处理所有像纯文本一样的文字?

Is there a way to avoid this problem and have the code handle all the text like plain text?

因为我想搜索特殊字符,我宁愿不禁止输入它们。在开始时我虽然以编程方式在执行搜索之前为所有特殊字符添加了一个转义反斜杠,但也许有一些更聪明的方法?

Because I would like to search also for special characters, I would like to prefer to not interdict to enter them. At the beginning I though to programmatically add an escape backslash to all special character before to perform a search, but maybe there are some more smart approaches?

这是代码我使用(基于本教程:)

Here is the code I'm using (based on this tutorial: NSRegularExpression Tutorial: Getting Started)

struct SearchOptions {
    let searchString: String
    var replacementString: String
    let matchCase: Bool
    let wholeWords: Bool
}

extension NSRegularExpression {
    convenience init?(options: SearchOptions) {
        let searchString = options.searchString
        let isCaseSensitive = options.matchCase
        let isWholeWords = options.wholeWords

        // 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 it's whole word put the string between word boundary \b
        if isWholeWords {
            pattern = "\\b\(searchString)\\b" // the second \ is used as escape
        }

        do {
            try self.init(pattern: pattern, options: regexOption)
        } catch {
            print(error)
        }
    }
}


推荐答案

您可以使用:

You may use NSRegularExpression.escapedPatternForString:

因此,你需要

var pattern = NSRegularExpression.escapedPatternForString(searchString)

另外,请注意这件作品:

Also, note that this piece:

if isWholeWords {
    pattern = "\\b\(searchString)\\b"

如果用户输入

可能会失败(text)并希望将其作为整个单词进行搜索。匹配整个单词的最佳方法是通过在搜索词的两端禁止单词字符的外观:

might fail if a user inputs (text) and wishes to search for it as a whole word. The best way to match whole words is by means of lookarounds disallowing word chars on both ends of the search word:

if isWholeWords {
    pattern = "(?<!\\w)" + NSRegularExpression.escapedPatternForString(searchString) + "(?!\\w)"

这篇关于在Swift中使用Regex进行简单搜索时,如何避免因搜索字符串中的特殊字符而导致的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 17:13