我想从字符串中提取YAML块。此块不是典型的YAML,以---
开头和结尾。我希望这些标记之间的文本没有标记本身。下面是一个测试字符串(swift 4):
let testMe = """
---
# Metadata
title: hum
author: jecatatu
email: jecatatu@gmail.com
---
This is more text outside the yaml block
"""
在纯正则表达式中,模式为---([\s\S]*?)---
。我最初的想法,因为我是初学者是使用VerbalExpressions,但我无法使用Verbal Expression重现这种模式。我得到的最接近的是:
let tester = VerEx()
.find("---")
.anything()
.find("---")
如何在Swift中使用正则表达式从字符串中提取(但没有)---?
答案 0 :(得分:3)
您可以使用String方法
func range<T>(of aString: T, options mask: String.CompareOptions = default, range searchRange: Range<String.Index>? = default, locale: Locale? = default) -> Range<String.Index>? where T : StringProtocol
并使用正则表达式模式查找此SO answer中两个字符串之间的所有字符:
let testMe = """
---
# Metadata
title: hum
author: jecatatu
email: jecatatu@gmail.com
---
This is more text outside the yaml block
"""
let pattern = "(?s)(?<=---\n).*(?=\n---)"
if let range = testMe.range(of: pattern, options: .regularExpression) {
let text = String(testMe[range])
print(text)
}
# Metadata
title: hum
author: jecatatu
email: jecatatu@gmail.com
答案 1 :(得分:1)
您可以使用此正则表达式:
let regex = "(?s)(?<=---).*(?=---)"
感谢@leo在接受的答案中显示正确的正则表达式
然后使用此功能可以评估它:
func matches(for 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 let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
然后使用它
let matched = matches(for: regex, in: yourstring)
print(matched)
SourceSafe https://stackoverflow.com/a/27880748/1187415