0

I am extending rouge shell lexer for my jekyll site and I want to do the following.

  1. Match --word. Capture word, discard --.
  2. Match <word>. Capture word, discard both < and >.
  3. Match word=anyNumber.word. Capture word and anyNumber.word, discard =.

First I have tried /(?=-+)\w/, didn't match anything, then I tried to do reverse and discard word such as /-+(?=\w*)/, and it worked. What I am doing wrong?

Dennis Grinch
  • 353
  • 3
  • 13
  • 1
    Adding a small example and the desired result would be helpful. If you do that, be sure to assign a variable to each input value (`str = "..."`) so that readers can refer to the variables without having to define them. – Cary Swoveland Jun 01 '16 at 01:15

2 Answers2

2

I suspect you're overthinking this. You don't need lookahead or lookbehind here.

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"]
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
0
str = "--hopscotch <dodgeball> cat=9.lives"

str[/(?<=\-\-)\w+/]
  #=> "hopscotch" 
str[/(?<=\<)\w+(?=\>)/]
  #=> "dodgeball" 
str.scan /(?:\w+(?=\=))|(?<=\=)\d+\.\w+/
  #=> ["cat", "9.lives"] 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100