Swift Regex 用于提取括号之间的单词 [英] Swift Regex for extracting words between parenthesis
问题描述
你好,我想提取 () 之间的文本.
Hello i wanna extract the text between ().
例如:
(some text) some other text -> some text
(some) some other text -> some
(12345) some other text -> 12345
括号之间的字符串的最大长度应为 10 个字符.
the maximum length of the string between parenthesis should be 10 characters.
(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)
}
}
效果很好,但匹配的是:
which works nicely but the matches are :
(some text) some other text -> (some text)
(some) some other text -> (some)
(12345) some other text -> (12345)
并且不匹配 <=10 因为 () 也被计算在内.
and doesn't match <=10 because () are counted also.
我该如何更改上面的代码来解决这个问题?我还想删除 if (match.characters.count <= 10)
通过扩展正则表达式来保存长度信息.
How can i change the code above to solve that? I would like also to remove the if (match.characters.count <= 10)
by extending the regex to hold the length info.
推荐答案
可以使用
"(?<=\\()[^()]{1,10}(?=\\))"
查看正则表达式演示
模式:
(?<=\\()
- 断言在当前位置之前存在(
,如果没有则匹配失败[^()]{1,10}
- 匹配除(
和)
之外的 1 到 10 个字符(替换[^()]
和\w
如果你只需要匹配字母数字/下划线字符)(?=\\))
- 检查当前位置后是否有文字)
,如果没有则匹配失败.
(?<=\\()
- asserts the presence of a(
before the current position and fails the match if there is none[^()]{1,10}
- matches 1 to 10 characters other than(
and)
(replace[^()]
with\w
if you need to only match alphanumeric / underscore characters)(?=\\))
- checks if there is a literal)
after the current position, and fail the match if there is none.
如果您可以调整代码以获取范围 1(捕获组)的值,您可以使用更简单的正则表达式:
If you can adjust your code to get the value at Range 1 (capture group) you can use a simpler regex:
"\\(([^()]{1,10})\\)"
查看正则表达式演示.您需要的值位于 Capture 组 1 内.
See the regex demo. The value you need is inside Capture group 1.
这篇关于Swift Regex 用于提取括号之间的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!