【发布时间】:2018-08-30 20:25:27
【问题描述】:
我有以下功能
static func replaceAtSignNotation(_ text : String) -> String {
var source = text
let wholePattern = "@\\[[a-z0-9-\\-]+\\]\\((\\w+)\\)"
let typePattern = "(?<=]\\()[^)]+(?=\\))"
if let wholeRange = source.range(of: wholePattern, options: .regularExpression) {
if let typeRange = source.range(of: typePattern, options: .regularExpression) {
let username = source[typeRange]
source.replaceSubrange(wholeRange, with: "@\(username)")
}
} else {
return text
}
return replaceAtSignNotation(source)
}
在寻找模式方面做得很好,例如:
@[a12-3asd-32](john)
@[b12-32d1-23](martha)
并允许我捕获用户名,但某些用户名确实包含“-”,例如:
@[c12-12d1-13](john-user-1)
但我当前的正则表达式没有捕捉到这些情况。知道如何调整我的正则表达式来捕获这些情况吗?
【问题讨论】:
-
为什么要使用两种模式?为什么不使用
NSRegularExpression并使用组来分隔您想要的内容?