Regex 用于提取括号之间单词的Swift正则表达式
你好,我想提取()之间的文本 例如:Regex 用于提取括号之间单词的Swift正则表达式,regex,swift,Regex,Swift,你好,我想提取()之间的文本 例如: (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!
(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)
}
}
与不匹配这将起作用
\((?=.{0,10}\)).+?\)
这也会起作用
\((?=.{0,10}\))([^)]+)\)
正则表达式分解
你可以用
"(?<=\\()[^()]{1,10}(?=\\))"
看。您需要的值位于捕获组1内
\( #Match the bracket literally
(?=.{0,10}\)) #Lookahead to check there are between 0 to 10 characters till we encounter another )
([^)]+) #Match anything except )
\) #Match ) literally
"(?<=\\()[^()]{1,10}(?=\\))"
"\\(([^()]{1,10})\\)"