import Foundation
let pattern = #"^((?:\[.+?:.*?\])+)(.*)$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
[ar:胡彦斌]
[ti:月光]
[00:00.86]月光(秦时明月主题曲)
[00:06.31]歌手 胡彦斌
[00:08.68]作词 林文炫
[00:10.49]作曲 胡彦斌
[00:20.11]月光色
[00:22.30]女子香
[00:24.51]泪断剑
[00:26.70]情多长
[00:28.95]有多痛
[00:30.97]无字想
[00:33.35][00:33.35]忘了你
[00:39.43]孤单魂
[00:41.51]随风荡
[00:43.57]谁去笑
[00:45.87]痴情郎
[00:48.03]这红尘的战场
[00:52.95]千军万马有谁能称王
[01:01.69]过情关
[01:06.00]谁敢闯
[01:10.42]望明月
[01:15.62]心悲凉
[01:19.13]千古恨
[01:23.45]轮回尝
[01:27.76]眼一闭
[01:32.71]谁最狂
[01:38.90]这世道的无常
[01:43.23]注定敢爱的人一生伤
[02:07.33]月光色
[02:09.20]女子香
[02:11.49]泪断剑
[02:13.58]情多长
[02:15.80]有多痛
[02:17.87]无字想
[02:20.23]忘了你
[02:26.21]孤单魂
[02:28.20]随风荡
[02:30.56]谁去笑
[02:32.64]痴情郎
[02:34.94]这红尘的战场
[02:39.70]千军万马有谁能称王
[02:48.65]过情关
[02:52.66]谁敢闯
[02:57.34]望明月
[03:02.44]心悲凉
[03:05.97]千古恨
[03:09.99]轮回尝
[03:14.67]眼一闭
[03:19.95]谁最狂
[03:30.06]过情关
[03:34.34]谁敢闯
[03:38.78]望明月
[03:43.92]心悲凉
[03:47.58]千古恨
[03:51.50]轮回尝
[03:55.96]眼一闭
[04:01.51]谁最狂
[04:07.21]这世道的无常
[04:21.34]注定敢爱的人一生伤
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression