你好,我想提取 () 之间的文本。
例如:
(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)
并且不匹配 <=10 因为 () 也被计算在内。
我如何修改上面的代码来解决这个问题?我还想删除 if (match.characters.count <= 10)
通过扩展正则表达式来保存长度信息。
请您参考如下方法:
你可以使用
"(?<=\\()[^()]{1,10}(?=\\))"
参见 regex demo
模式:
-
(?<=\\()
- 断言(
的存在在当前位置之前,如果没有则匹配失败 -
[^()]{1,10}
- 匹配(
以外的 1 到 10 个字符和)
(如果您只需要匹配字母数字/下划线字符,请将[^()]
替换为\w
) -
(?=\\))
- 检查是否有文字)
在当前位置之后,如果没有则匹配失败。
如果您可以调整代码以获取范围 1(捕获组)的值,则可以使用更简单的正则表达式:
"\\(([^()]{1,10})\\)"
参见 regex demo .您需要的值在捕获组 1 中。