我已经看了一段时间了,我想知道如何在一个大字符串中检测一个子字符串的多个位置。例如:
let text = "Hello, playground. Hello, playground"
let range: Range<String.Index> = text.rangeOfString("playground")! //outputs 7...<17
let index: Int = text.startIndex.distanceTo(range.startIndex) //outputs 7, the location of the first "playground"
我使用这段代码来检测子字符串在字符串中出现的第一个位置,但是它有可能检测到第二个出现的“游乐场”的位置,然后是第三个,等等。
发布于 2016-03-02 22:25:36
这将为您提供一个带有“操场”的NSRanges数组。
let regex = try! NSRegularExpression(pattern: "playground", options: [.caseInsensitive])
let items = regex.matches(in: text, options: [], range: NSRange(location: 0, length: (text as NSString).length))
let ranges: [NSRange] = items.map{$0.range}
然后得到字符串:
let occurrences: [String] = ranges.map{String((text as NSString).substring(with:$0))}
发布于 2018-08-29 11:43:35
Swift 4
let regex = try! NSRegularExpression(pattern: fullNameArr[1], options: [.caseInsensitive])
let items = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count))
let ranges: [NSRange] = items.map{$0.range}
let occurrences: [String] = ranges.map{String((str as NSString).substring(with: $0))}
https://stackoverflow.com/questions/35759088
复制相似问题