-1

I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Wboy
  • 2,452
  • 2
  • 24
  • 45

3 Answers3

1

Just escape the | : (?<=\|).*?(?=>). Without it, the positive lookbehind means match anything

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

You forgot to escape the pipe (|), which is now interpreted as the indicator for an alternation

Your regex with the escaped pipe:

(?<=\|).*?(?=>)

Here you can see the result

ScintillatingSpider
  • 338
  • 1
  • 9
  • 14
  • Doesn't find all of the names though – Wboy Jul 06 '17 at 10:15
  • 1
    How do you mean? can you give an example of what is does and does not match? – ScintillatingSpider Jul 06 '17 at 10:16
  • Sorry i was testing it on regex101.com and it didnt show the results correctly! It works fine on ruby :) I'll accept your answer when the timer is up Thank you! :) – Wboy Jul 06 '17 at 10:17
  • No problem. The regex itself does indeed only match one occurrence, but will result in multiple matches combined with a global flag or when used with `scan()` (which will return each pattern match) – ScintillatingSpider Jul 06 '17 at 10:46
0

Try this:

text.scan(/\|(\w*)\>/).flatten
# Returns => ["potato", "tomato"]

Not exactly sure why this works. Something to do with greedy and non-greedy matching. See this

aBadAssCowboy
  • 2,440
  • 2
  • 23
  • 38