ios - 在 swift 中使用正则表达式提取和打印字符串
问题描述
我希望在正则表达式上使用 swift 提取和打印字符串,但我一直坚持如何去做。我是 swift 和 swift 上的正则表达式的新手,所以很难弄清楚
在下面的示例中,我想打印 62AD 和 21BC(方括号内的任何内容)。我只能想出这段代码,但这不会提取任何东西并给出一个 nil 值。换行符和引号是字符串的一部分
let output = "\"Living Room\" [62AD]\n Hub \"Living Room\" [21BC]:"
let range = NSRange(output.startIndex..<output.endIndex,in: output)
let patternToMatch1 = "\"Living Room\" [.*]+\n"
let patternToMatch2 = "Hub \"Living Room\" [^:]+:"
let captureRegex1 = try! NSRegularExpression(pattern: patternToMatch1, options: [])
let captureRegex2 = try! NSRegularExpression(pattern: patternToMatch2, options: [])
let matches1 = captureRegex1.matches(in: output,options: [],range: range)
guard let match1 = matches1.first else {
throw NSError(domain: "", code: 0, userInfo: nil)
}
print("\(String(describing:match1))")
let matches2 = captureRegex2.matches(in: output,options: [],range: range)
guard let match2 = matches2.first else {
throw NSError(domain: "", code: 0, userInfo: nil)
}
print("\(String(describing:match2))")
解决方案
将您的固定正则表达式与此解决方案相结合:
import Foundation
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range(at: 1))}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
let output = "\"Living Room\" [62AD]\n Hub \"Living Room\" [21BC]:"
let patternToMatch1 = "\"Living Room\"\\s*\\[(.*?)]"
print(matches(for: patternToMatch1, in:output))
结果:["62AD", "21BC"]
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
"Living Room" '"Living Room"'
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
] ']'
推荐阅读
- javascript - 观察深层对象变化时不会触发 VueJS Watcher
- python - JSONEncoder double jsonify objects extending from a class in python
- python-3.x - 将numpy数组拆分为固定长度
- android - Flutter 中的设备返回按钮控制
- microsoft-graph-api - 您可以将名称传递到 Teams 中的加入会议链接吗?
- c# - FileHelperEngine 的字符编码错误
- python - Python脚本被“杀死”
- python - 如果无法将元素转换为浮点数,则从列表中删除元素
- java - Hibernate 模式生成考虑来自其他 Maven 模块的实体
- r - 如何从多个 lavaan 模型中提取一个特定系数?