如何在字符串中的降价之间区分代码

How to individuate code between markdown in string

我正在创建一个文本视图,用户可以在其中插入代码片段。
我希望他们能够像这样插入降价:

``` some text here `

然后我想区分降价之间的文本并对其应用一些特征。

假设一个字符串可以包含更多降价,我怎样才能得到降价内的所有字符串?

假设我有以下字符串:

"In Swift a ```UIView` is An object that manages the content for a rectangular area on the screen. It subclasses ```UIResponder`. A ```UIPickerView` is a subclass of ```UIView`"

我想个性化子字符串:UIView、UIResponder、UIPickerView、UIView。
即所有包含在```和`.

之间的子字符串

我找到了一些解决方案,其中包括使用超级复杂的 for 循环,但我确信我们有更简单的方法来使用一些我无法使用的字符串方法...

您可以像这样使用正则表达式 -

import Foundation

let input = "In Swift a ```UIView` is An object that manages the content for a rectangular area on the screen. It subclasses ```UIResponder`. A ```UIPickerView` is a subclass of ```UIView`"
do {
    let regex = try NSRegularExpression(pattern: #"(```.*?`)"#)
    let matches = regex.matches(in: input, range: NSRange(input.startIndex..., in: input))
    var results: [String] = []
    let nsStringInput = input as NSString
    for match in matches {
        results.append(nsStringInput.substring(with: match.range))
    }
    print(results)
}
catch {
    /// Handle error
}

输出-

[
    "```UIView`", 
    "```UIResponder`", 
    "```UIPickerView`", 
    "```UIView`"
]