2016-04-29 199 views
1

你好,我想提取()之间的文本。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! 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)

回答

3

您可以使用

"(?<=\\()[^()]{1,10}(?=\\))" 

见​​

模式:

  • (?<=\\() - 断言当前POSI前(的存在重刑和失败的比赛如果没有,则
  • [^()]{1,10} - 比()等1到10个字符相匹配(含\w取代[^()]如果你只需要匹配字母/下划线)
  • (?=\\)) - 如果有一个检查在当前位置之后的文字),如果没有则匹配失败。

如果你能调整你的代码来获得在范围1(摄影组)的值,你可以使用一个简单的正则表达式:

"\\(([^()]{1,10})\\)" 

regex demo。您需要的值在Capture组1中。

2

这将工作

\((?=.{0,10}\)).+?\) 

Regex Demo

这也将工作

\((?=.{0,10}\))([^)]+)\) 

Regex Demo

正则表达式击穿

\(#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 
相关问题