Swift 2.0: NSRangeException, Range or index out of bounds
上下文:我来自15至20年的JavaScript,Ruby和(现代)PHP。过去一年来,我一直在Swift公司打球,对Cocoa来说我是新手。
这是我在Xcode 7.0β2中运行的简化测试用例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #! /usr/bin/env swift import Foundation // Extend the String object with helpers extension String { // String.replace(); similar to JavaScript's String.replace() and Ruby's String.gsub() func replace(pattern: String, replacement: String) -> String { // Debugging print(self.characters.count) print(NSMakeRange(0, self.characters.count - 1)) let regex = try! NSRegularExpression( pattern: pattern, options: [.CaseInsensitive] ) return regex.stringByReplacingMatchesInString( replacement, options: [.Anchored], range: NSMakeRange(0, self.characters.count - 1), withTemplate:"xx" ) } } let prefix ="abc 123".replace("\\\\s+", replacement:"") print(prefix) |
两条调试行显示:
1 2 | 11 (0,10) |
之后,该应用程序崩溃并显示以下消息:
2015-06-24 23:18:45.027 swift[42912:648900] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSRegularExpression enumerateMatchesInString:options:range:usingBlock:]: Range or index out of bounds'
我已经查看了以下文档,但没有任何内容对我有帮助:
- NSRegularExpression类参考
- NSRegularExpression / enumerateMatchesInString:options:range:usingBlock:
我只能认为该问题与将
正如我在标题中所写,我正在使用Swift 2.0。
我看到stringByReplacingMatchesInString的第一个参数是"替换"。这应该是"自我"吗?
@Ben回答后,我感到很愚蠢。这开始了更多的探索,我想通了。这是代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #! /usr/bin/env swift import Foundation // Extend the String object with helpers extension String { // String.replace(); similar to JavaScript's String.replace() and Ruby's String.gsub() func replace(pattern: String, replacement: String) -> String { let regex = try! NSRegularExpression( pattern: pattern, options: [.CaseInsensitive] ) return regex.stringByReplacingMatchesInString( self, options: [.WithTransparentBounds], range: NSMakeRange(0, self.characters.count), withTemplate: replacement ) } } let prefix ="abc 123".replace("(\\\\s+)", replacement:"") print(prefix) |
也许:
1 2 3 4 5 6 7 8 | Return regex.stringByReplacingMatchesInString{ MainstringYouWantToReplaceSomethinIn, options: [.Anchored], range: NSMakeRange(0,self.MainstringYouWantToReplaceSomethinIn.count - 1), withTemplate:"xx" ) } } |