MIchal Skoda
MIchal Skoda

Reputation: 57

Match returns another outpu

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!

Upvotes: 0

Views: 30

Answers (2)

Stefan
Stefan

Reputation: 114188

[...] 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:/">

Upvotes: 2

borjagvo
borjagvo

Reputation: 2081

str = "https://youtu.be/KMBBjzp5hdc"
matches = str.match(/(https:\/\/youtu.be\/)(.+)/)
matches[1]

Outputs:

"https://youtu.be/"

Upvotes: 0

Related Questions