如何在 Swift 中的“---”之间提取多行字符串

How to extract multiline string between "---" in Swift

我想从字符串中提取 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 中使用正则表达式从字符串中提取(但没有)之间的任何内容?

您可以使用这个正则表达式:

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([=11=].range, in: text)!])
    }
} catch let error {
    print("invalid regex: \(error.localizedDescription)")
    return []
}

}

那就用吧

let matched = matches(for: regex, in: yourstring)
print(matched)

SourceSafe

您可以使用字符串方法

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