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



我想从字符串中提取一个 YAML 块。此块不是典型的 YAML,并且以 --- 开头和结尾。我希望这些标记之间的文本没有标记本身。下面是一个测试字符串(swift 4):

let testMe = """
--- 
# Metadata
title: hum
author: jecatatu
email: jecatatu@gmail.com
---
This is more text outside the yaml block
"""

在纯正则表达式中,模式将是---([sS]*?)--- .因为我是初学者,我最初的想法是使用语言表达,但我无法使用口头表达重现这种模式。我得到的最接近的是:

let tester = VerEx()
    .find("---")
    .anything()
    .find("---")

如何在 Swift 中使用正则表达式从字符串中提取介于(但没有)---的任何内容?

您可以使用字符串方法

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 答案中查找两个字符串之间的所有字符:

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

您可以使用此正则表达式:

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)

源安全 https://stackoverflow.com/a/27880748/1187415

最新更新