我正在使用 Swift 框架將一些 Markdown 轉換為 HTML。
我希望能夠在大多數框架提供的正常默認元素之外創建適合我需求的自定義 Markdown 元素。
假設我有以下自定義 Markdown:
# My heading
This is normal text with a [link](/).
Below is my custom markdown element called `!file`:
[!file title="This is my title" icon="rocket"](file.txt)
我如何能夠將屬性提取到陣列或字典中,以便將它們轉換為 HTML?
例如:
// from this: [!file title="This is my title" icon="rocket"](file.txt)
attributes = [
"title" : "This is my title",
"icon" : "rocket",
"item" : "file.txt"
]
or from this: [!file](../files/docs/terms.pdf)
attributes = [
"title" : "",
"icon" : "",
"item" : "../files/docs/terms.pdf"
]
我最初嘗試使用.split(" "),但由于title="This is my title"包含空格,因此它會在這些專案處拆分。
我想標題和圖示是可選的nil,默認情況下是。
除了標準的 iOS/macOS 使用之外,我還沒有真正使用過 Swift,所以當只依賴 Foundation 時,我有點迷茫。
uj5u.com熱心網友回復:
如果我沒有完全誤解這一點,您需要一個正則運算式來匹配文本中的自定義!file元素并將結果轉換為 swift 集合。
為此,我使用了帶有命名組的正則運算式模式
let pattern = #"\[!file\s*(title="(?<title>.*)")?\s*(icon="(?<icon>.*)")?\]\((?<file>.*)\)"#
或者您可以使用@RizwanM.Tuman 的答案中的模式,這可能更有效,并且在使用命名組時看起來像這樣
let pattern = #"\[!file(?:\s*title="(?<title>[^"]*?)"\s*icon="(?<icon>[^"]*?)")?]\((?<file>[^)] )\)"#
然后將像這樣完成結果的匹配和提取
let regex = try NSRegularExpression(pattern: pattern, options: [])
let fullRange = NSRange(text.startIndex..<text.endIndex, in: text)
var components = [String: String]()
if let match = regex.firstMatch(in: text, options: [], range: fullRange) {
for component in ["title", "icon", "file"] {
let componentRange = match.range(withName: component)
if componentRange.location != NSNotFound,
let range = Range(componentRange, in: text)
{
components[component] = String(text[range])
}
}
}
這假設只有一個此自定義元素要匹配,但如果您有多個,則需要像這樣遍歷匹配項
var allMarkdowns = [[String: String]]()
regex.enumerateMatches(in: text, options: [], range: fullRange) { (match, _, _) in
guard let match = match else { return }
var components = [String: String]()
for component in ["title", "icon", "file"] {
let componentRange = match.range(withName: component)
if componentRange.location != NSNotFound,
let range = Range(componentRange, in: text) {
components[component] = String(text[range])
}
}
allMarkdowns.append(components)
}
一個例子
let text = """
# My heading
This is normal text with a [link](/).
Below is my custom markdown element called `!file`:
[!file title="This is my title" icon="rocket"](file.txt)
bla bla
[!file](../files/docs/terms.pdf)
"""
對此運行第二個解決方案將產生
[[“file”:“file.txt”,“title”:“這是我的標題”,“icon”:“rocket”],[“file”:“../files/docs/terms.pdf”] ]
uj5u.com熱心網友回復:
你可以試試這個正則運算式:
\[!file(?:\s*title="([^"]*?)"\s*icon="([^"]*?)")?]\(([^)] )\)
這里標題和圖示屬性是可選的
- 標題組 1
- 第 2 組用于圖示
- 專案組 3
演示:Regex101
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447354.html
