gpt4 book ai didi

ios - 在 Swift 中使用 Regex 进行简单搜索时,如何避免由于搜索字符串中的特殊字符而导致的错误?

转载 作者:可可西里 更新时间:2023-11-01 02:16:13 25 4
gpt4 key购买 nike

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

我得到的错误是这样的:

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

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

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

这是我正在使用的代码(基于本教程: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)
}
}
}

最佳答案

您可以使用 NSRegularExpression.escapedPatternForString :

Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters.

因此,你需要

var pattern = NSRegularExpression.escapedPatternForString(searchString)

另外,请注意这件作品:

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

如果用户输入 (text) 并希望搜索整个单词,则可能会失败。匹配整个单词的最佳方法是通过环视来禁止搜索词两端的单词字符:

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

关于ios - 在 Swift 中使用 Regex 进行简单搜索时,如何避免由于搜索字符串中的特殊字符而导致的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38375557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com