在Swift中移除Wikitext超链接格式的问题求助
解决Wikitext超链接文本提取问题
需求规则
- 无分隔符
|的链接:[[user interface]]→user interface(仅移除[[和]]) - 带分隔符
|的链接:[[Telephone call|calls]]→calls(移除[[到|的内容及]],保留|后的文本)
当前代码问题
- 正则仅覆盖了带
|的链接场景,未处理无|的情况 - 替换时使用固定字符串
{removed},未利用捕获组提取需要保留的目标文本
修正后的代码
extension String { func replacingOccurrencesHyperlinks() -> String { let regExpr = "\\[\\[(?:[^|\\]]+\\|)?(.+?)\\]\\]" return replacingOccurrences(of: regExpr, with: "$1", options: .regularExpression) } }
正则表达式解释
\\[\\[:匹配链接开头的[[(?:[^|\\]]+\\|)?:非捕获可选组,匹配|前的链接目标部分(仅在带|的链接中生效)[^|\\]]+:匹配除|和]之外的任意字符,即|前的原始链接内容\\|:匹配分隔符|?:标记该组为可选,兼容无|的链接场景
(.+?):捕获组,提取需要保留的文本(无|时为括号内全部内容,有|时为|到]]之间的内容)\\]\\]:匹配链接结尾的]]
测试验证
输入:
The iPhone has a [[user interface]] built around a [[multi-touch]] screen. It connects to [[cellular network]]s or [[Wi-Fi]], and can make [[Telephone call|calls]], [[web browser|browse the web]], [[camera phone|take pictures]], [[portable media player|play music]] and send and receive [[email]]s and [[text messaging|text messages]].
输出:
The iPhone has a user interface built around a multi-touch screen. It connects to cellular networks or Wi-Fi, and can make calls, browse the web, take pictures, play music and send and receive emails and text messages.
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

