0

after inserting input value "https://youtu.be/KMBBjzp5hdc" the code returns output value "https://youtu.be/"

str = gets.chomp.to_s
puts /.*[=\/]/.match(str)

I do not understand why as i would expect https:/

Thanks for advise!

  • Can add input and output to the question instead of the links? – Fabio Jan 20 '21 at 05:45
  • 1
    Does this answer your question? [How can I write a regex which matches non greedy?](https://stackoverflow.com/questions/11898998/how-can-i-write-a-regex-which-matches-non-greedy) – iBug Jan 20 '21 at 05:59
  • Short answer: `/.*?[=\/]/.match str` – iBug Jan 20 '21 at 05:59

2 Answers2

2

[...] the code returns output value "https://youtu.be/" [...] I do not understand why as i would expect https:/

Your regexp /.*[=\/]/ matches:

  • .* zero or more characters
  • [=\/] followed by a = or / character

In your example string, there are 3 candidates that end with a / character: (and none ending with =)

  1. https:/
  2. https://
  3. https://youtu.be/

Repetition like * is greedy by default, i.e. it matches as many characters as it can. From the 3 options above, it matches the longest one which is https://youtu.be/.

You can append a ? to make the repetition lazy, which results in the shortest match:

"https://youtu.be/KMBBjzp5hdc".match(/.*?[=\/]/)
#=> #<MatchData "https:/">
Stefan
  • 109,145
  • 14
  • 143
  • 218
0
str = "https://youtu.be/KMBBjzp5hdc"
matches = str.match(/(https:\/\/youtu.be\/)(.+)/)
matches[1]

Outputs:

"https://youtu.be/"
borjagvo
  • 1,802
  • 2
  • 20
  • 35