gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:39:34 25 4
gpt4 key购买 nike

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

最佳答案

你可以使用字符串方法

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

关于regex - 如何在Swift中提取 "---"之间的多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46997865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com