你好,我想提取 () 之间的文本。
例如 :
(some text) some other text -> some text
(some) some other text -> some
(12345) some other text -> 12345
Run Code Online (Sandbox Code Playgroud)
括号之间的字符串的最大长度应为 10 个字符。
(TooLongStri) -> nothing matched because 11 characters
Run Code Online (Sandbox Code Playgroud)
我目前拥有的是:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
效果很好,但匹配的是:
(some text) some other text -> (some text)
(some) some other text -> (some)
(12345) some other text -> (12345)
Run Code Online (Sandbox Code Playgroud)
并且 不匹配 <=10,因为 () 也被计算在内。
我该如何更改上面的代码来解决这个问题?我还想if (match.characters.count <= 10)通过扩展正则表达式来保存长度信息来删除 。
您可以使用
"(?<=\\()[^()]{1,10}(?=\\))"
Run Code Online (Sandbox Code Playgroud)
请参阅正则表达式演示
图案:
(?<=\\()- 断言当前位置之前存在 a (,如果不存在则匹配失败[^()]{1,10}(- 匹配 1 到 10 个除and之外的字符)(如果您只需要匹配字母数字/下划线字符,请替换[^()]为)\w(?=\\))- 检查当前位置后面是否有文字),如果没有则匹配失败。如果您可以调整代码以获取范围 1(捕获组)的值,则可以使用更简单的正则表达式:
"\\(([^()]{1,10})\\)"
Run Code Online (Sandbox Code Playgroud)
请参阅正则表达式演示。您需要的值位于捕获组 1 内。
| 归档时间: |
|
| 查看次数: |
3220 次 |
| 最近记录: |