【发布时间】:2016-04-29 14:48:04
【问题描述】:
您好,我想提取 () 之间的文本。
例如:
(some text) some other text -> some text
(some) some other text -> some
(12345) some other text -> 12345
括号之间的字符串的最大长度应为 10 个字符。
(TooLongStri) -> nothing matched because 11 characters
我目前拥有的是:
let regex = try! NSRegularExpression(pattern: "\\(\\w+\\)", options: [])
regex.enumerateMatchesInString(text, options: [], range: NSMakeRange(0, (text as NSString).length))
{
(result, _, _) in
let match = (text as NSString).substringWithRange(result!.range)
if (match.characters.count <= 10)
{
print(match)
}
}
效果很好,但匹配的是:
(some text) some other text -> (some text)
(some) some other text -> (some)
(12345) some other text -> (12345)
不匹配
如何更改上面的代码来解决这个问题?我还想通过扩展正则表达式来删除if (match.characters.count <= 10)以保存长度信息。
【问题讨论】: