匹配一个字符串,但只捕获它在红宝石中匹配的子字符串

时间:2016-06-01 01:11:48

标签: ruby regex jekyll rouge

我正在为我的rouge网站扩展jekyll shell词法分析器,我想要执行以下操作。

  1. 匹配--word。抓取word,弃掉--
  2. 匹配<word>。抓取word,弃掉<>
  3. 匹配word=anyNumber.word。抓取wordanyNumber.word,弃掉=
  4. 首先我尝试了/(?=-+)\w/,没有匹配任何内容,然后我尝试反向并放弃word,例如/-+(?=\w*)/,它就有效了。我做错了什么?

2 个答案:

答案 0 :(得分:2)

我怀疑你是在思考这个问题。你不需要前瞻或后视。

str = "foo --word1 <word2> word3=anyNumber.word4"

p /--(\w+)/.match(str).captures
# => ["word1"]

p /<([^>]+)>/.match(str).captures
# => ["word2"]

p /(\w+)=([\w.]+)/.match(str).captures
# => ["word3", "anyNumber.word4"]

答案 1 :(得分:0)

str = "--hopscotch <dodgeball> cat=9.lives"

str[/(?<=\-\-)\w+/]
  #=> "hopscotch" 
str[/(?<=\<)\w+(?=\>)/]
  #=> "dodgeball" 
str.scan /(?:\w+(?=\=))|(?<=\=)\d+\.\w+/
  #=> ["cat", "9.lives"]