gpt4 book ai didi

ios - 为什么我的正则表达式中有多个捕获组会使我的应用程序崩溃?

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

无论正则表达式是什么,>1 个捕获组都会使此代码崩溃并出现以下错误。

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[__NSCFString substringWithRange:]:范围 {9223372036854775807, 0} 超出范围;字符串长度 279'

public extension String
{
//Multi use parsing function
func regexParse(pattern:String, captureGroup:Int, caseSensitive:Bool) ->[String]
{
do
{
//Creates empty results array.
var resultsArray = [""]

//Sets Case sensitivity
var caseSensitivity = NSRegularExpressionOptions.CaseInsensitive
if(caseSensitive)
{
caseSensitivity = NSRegularExpressionOptions.init(rawValue: 0)
}

//Sets regex to correct pattern
let regex = try NSRegularExpression(pattern: pattern, options: caseSensitivity)
//Converts string to NSString as swift doesn't support regex
let nsString = self as NSString

//Sets parsing range to the entire string
let all = NSMakeRange(0, nsString.length)

//Enumerates through all matches and extracts the 1st capture bracket for each match and adds it to the resultsArray.

regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all)
{
(result: NSTextCheckingResult?, _, _) in let theResult = nsString.substringWithRange(result!.rangeAtIndex(captureGroup))
resultsArray.append(theResult)
} //!!>>>>>>>>Error occurs here after skipping MatchingOptions content.!!
return resultsArray

}
catch
{
print("Invalid regex")
return(["Error"])
}
}

最佳答案

Range {9223372036854775807, 0}{NSNotFound, 0},这意味着没有匹配。

来自文档

Some regular expressions (though not the example pattern) can successfully match a zero-length range, so the comparison of the resulting range with {NSNotFound, 0} is the most reliable way to determine whether there was a match or not

例如在 enumerateMatchesInString 中执行检查

regex.enumerateMatchesInString(self, options: [], range: all) { (result: NSTextCheckingResult?, _, _) in
let capturedRange = result!.rangeAtIndex(captureGroup)
if !NSEqualRanges(capturedRange, NSMakeRange(NSNotFound, 0)) {
let theResult = nsString.substringWithRange(capturedRange)
resultsArray.append(theResult)
}
}

关于ios - 为什么我的正则表达式中有多个捕获组会使我的应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415678/

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