[00:13.00]hellow [00:23.00]my God [00:43.00]
从上面的文本中,我想获取[..]
答案应为[00:13:00,00:23:00,00:43:00]
我当前收到此错误:
致命错误:“尝试!”表达式意外引发错误:Error Domain = NSCocoaErrorDomain代码= 2048“值“ \ [(。*?)] \”无效。”
下面是我尝试过的一些正则表达式:
\\[(.*?)]\\
\\[(.*?)\\]
\\[([^\\[\\]]*)\\]\\
\[(.*?]*)\]
\[(.*?)\]
\\[(.*?)]\\
答案 0 :(得分:0)
您需要使用"\\[(.*?)\\]"
或"(?<=\\[).*?(?=\\])"
这是一个简单的例子
func getMatches(with regex: String, in text: String) -> [String]? {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch {
print("invalid regex")
return nil
}
}
let str = "[00:13.00]hellow [00:23.00]my God [00:43.00]"
let reg1 = "\\[(.*?)\\]"
let reg2 = "(?<=\\[).*?(?=\\])"
let vals1 = getMatches(with: reg1, in: str)
let vals2 = getMatches(with: reg1, in: str)
if let val = vals1 {
print("With reg1 : ",val)
}
if let val = vals2 {
print("\nWith reg2 : ",val)
}
输出:
答案 1 :(得分:0)
答案 2 :(得分:0)
发生错误是因为您必须用第二个反斜杠对每个反斜杠进行转义,并且转义反斜杠必须在方括号之前才被视为文字。
\\[(.*?)\\]
由于方括号内的格式始终相同,我的建议是捕获2位数字(\\d{2}
),冒号(:
),2位数字(\\d{2}
),句点(.
和2位数(\\d{2}
)括在括号中。
let string = "[00:13.00]hellow [00:23.00]my God [00:43.00]"
let regex = try! NSRegularExpression(pattern: "\\[(\\d{2}:\\d{2}.\\d{2})\\]")
let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
let result = matches.map { String(string[Range($0.range(at: 1), in: string)!]) }
print(result) // ["00:13.00", "00:23.00", "00:43.00"]
答案 3 :(得分:0)
可以使用以下代码在不使用正则表达式的情况下实现此目的:
let text = "[00:13.00]hellow [00:23.00]my God [00:43.00]"
let parts = text.split(separator: "[")
let values = parts.compactMap { (part: Substring) -> String? in
let parts = part.split(separator: "]", omittingEmptySubsequences: false)
guard parts.count == 2 else {
return nil
}
return String(parts[0])
}
print(values)