【问题标题】:Adding text to string将文本添加到字符串
【发布时间】:2018-08-06 17:12:40
【问题描述】:

我正在为一些动态降价设置样式,但是我用于样式设置的框架不支持链接的嵌套标签。

我需要有效地解析字符串并关闭样式标记标记:

    "__Some bold text [FIRST LINK](https://FIRSTLINK.COM \"FIRST LINK\"), more bold text.__\n\n additional text \n\n
 *some italic text[SECOND LINK](https://SECONDLINK.COM) ending text,*"

到这里:

    "__Some bold text __[FIRST LINK](https://FIRSTLINK.COM \"FIRST LINK\")__, more bold text.__\n\n additional text \n\n
 *some italic text*[SECOND LINK](https://SECONDLINK.COM)* ending text,*"

这仅适用于粗体和斜体文本。我开始沿着

的路线走
var str = "__Some bold text [FIRST LINK](https://FIRSTLINK.COM \"FIRST LINK\"), more bold text.__\n\n additional text \n\n *some italic text[SECOND LINK](https://SECONDLINK.COM) ending text,*"

    let bold = str.components(separatedBy: "__")
    for var string in bold {
        if let matchedIndex = string.index(of: "[") {
            string.insert(contentsOf: "__", at: matchedIndex)
        }
    }

但想知道,在 Swift 中有没有更好的方法来做到这一点?

编辑 - 为清楚起见 - 本质上我需要修改现有字符串以在链接标签之前具有封闭标签并在链接标签之后重新打开 - 这可以防止链接与样式标签嵌套并允许样式器框架相应地应用属性字符串

编辑 --- 与@Linus 注释一致,这里是正则表达式的结果(请注意在扩展的一侧运行这些以便能够在操场上进行测试

var str = "__Some bold text [FIRST LINK](https://FIRSTLINK.COM \"FIRST LINK\"), more bold text.__\n additional text \n *some italic text[SECOND LINK](https://SECONDLINK.COM) ending text,*\n__sfdadhfjkh [THIRD LINK](https://THIRDLINK.COM \"THIRD LINK\"), more bold text.__"

do {
    var regex = try NSRegularExpression(pattern:  "(\\[.*?\\))" , options: [.caseInsensitive])
    var newString = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.utf16.count), withTemplate: "__$1__")
    print("\nFirst regex  __$1__  \n\n\(newString)")

    regex = try NSRegularExpression(pattern:  "(\\[.*?\\))" , options: [.caseInsensitive])
        var newerString = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.utf16.count), withTemplate: "*$1*")
        print("\nSecond Regex *$1* \n\n"+newerString)
} catch { print("ERROR: searchFor regex (\("(\\[.*?\\))")) on string (\(str)) failed") }

打印结果

First regex  __$1__  

__Some bold text __[FIRST LINK](https://FIRSTLINK.COM "FIRST LINK")__, more bold text.__
 additional text 
 *some italic text__[SECOND LINK](https://SECONDLINK.COM)__ ending text,*
__sfdadhfjkh __[THIRD LINK](https://THIRDLINK.COM "THIRD LINK")__, more bold text.__

Second Regex *$1* 

__Some bold text *[FIRST LINK](https://FIRSTLINK.COM "FIRST LINK")*, more bold text.__
 additional text 
 *some italic text*[SECOND LINK](https://SECONDLINK.COM)* ending text,*
__sfdadhfjkh *[THIRD LINK](https://THIRDLINK.COM "THIRD LINK")*, more bold text.__

我需要在同一个字符串上同时修改斜体和强标记,以便将其传递给要设置样式的视图

【问题讨论】:

  • 看起来像是正则表达式的工作。
  • 你的例子不起作用,对吧?我没有看到在链接的右括号之后插入 __ 的任何内容。
  • @NRitH 这个例子并不完整,因为它只是表明我要走的路线......

标签: swift parsing markdown


【解决方案1】:

我正在使用以下字符串扩展,它允许您查找与某个正则表达式模式匹配的字符串并将其替换为其他字符串:

extension String {
    mutating func replaceOccurrence(ofPattern pattern: String, with replacementString: String) {
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
            self = regex.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, utf16.count), withTemplate: replacementString)
        } catch { print("ERROR: searchFor regex (\(pattern)) on string (\(self)) failed") }
    }
}

然后,您可以将(\[.*?\)) 替换为__$1__,如下所示:

str.replaceOccurrence(ofPattern: "(\\[.*?\\))", with: "__$1__")

说明

...如果你不熟悉regular expressions:

正则表达式:

( - 左括号,创建一个新组,稍后用于将匹配的字符串插入替换字符串
\[ - 匹配括号;需要使用\ 进行转义以禁用括号的正则表达式含义并改为匹配实际字符
.* - 匹配任何字符...
? - ...直到...
\) - ...下一个右括号;这个也需要转义以匹配实际字符,而不是创建新组
) - 关闭组

替换:

__ - 您的替换字符串:在这种情况下打开粗体范围
$1 - 在此处插入先前匹配的组 __ - 再次,您的替换字符串:在这种情况下关闭粗体范围

有趣的事实: 在 Swift 中,您需要转义转义字符,例如 \\ 以确保代码编译,因为 Xcode 认为,您正在尝试从字符串中转义字符在编译时。
这就是为什么正则表达式不是(\[.*?\)),而是(\\[.*?\\))

【讨论】:

  • 嘿,谢谢@Linus - 这看起来非常好 - 但是有几个问题。理想情况下,我只想修改文本而不是删除特定部分:例如运行以下命令: do { let regex = try NSRegularExpression(pattern: "(\[.*?\))" , options: [.caseInsensitive ]) var newString = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.utf16.count), withTemplate: "$1") print("第一个正则表达式 ( newString)") } catch { print("ERROR: searchFor regex (("(\[.*?\))")) on string ((str)) failed") }
  • 只返回第一个正则表达式一些粗体文本_FIRST LINK,更粗体文本。_
  • 我还需要为斜体运行相同的 - 将模式更改为 '"$1"' 返回 一些粗体文本 FIRST LINK,更粗体的文本。
  • 抱歉正则表达式是我从未掌握过的东西:(
  • 没问题。我很难理解你实际上想要做什么,因为我显然至少在某种程度上误解了它。你能用一个简洁的compact例子来说明你到底想要做什么吗? @user499846
猜你喜欢
  • 2015-10-06
  • 2011-08-30
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多