Ruby中的负面Lookbehind正则表达式 - 我如何仅匹配“\(”而不是“(”在Ruby中?

时间:2011-03-06 04:18:33

标签: ruby regex

我正在尝试编写一个匹配这些字符串的正则表达式:

title(Hello+World)             #=> [title, Hello+World]
title(\(Hello+World\))         #=> [title, \(Hello+World\)]
title((Hello+World))           #=> [title, (Hello+World)]
title(Well+Hello+World+!)      #=> [title, Well+Hello+World+!]
title(Well+\(Hello+World\)+!)  #=> [title, Well+\(Hello+World\)+!]
title(Well+(Hello+World)+!)    #=> [title, Well+(Hello+World)+!]

从开始(和结束)令牌中提取字符串的最简单方法是什么,因为令牌可以在它提取的字符串中的任何位置?

1 个答案:

答案 0 :(得分:2)

我不确定那些反斜杠是否应该保留结果,但是这里没有那个,是的,我不是在这里使用负反馈。

.scan(/(\w+)\(((?:\([^)]+\)|[^()]+)+)\)/)

=> [
["title", "Hello+World"], 
["title", "(Hello+World)"], 
["title", "(Hello+World)"], 
["title", "Well+Hello+World+!"], 
["title", "Well+(Hello+World)+!"], 
["title", "Well+(Hello+World)+!"]
]