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!
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!
[...] the code returns output value
"https://youtu.be/"[...] I do not understand why as i would expecthttps:/
Your regexp /.*[=\/]/ matches:
.* zero or more characters[=\/] followed by a = or / characterIn your example string, there are 3 candidates that end with a / character: (and none ending with =)
https:/https://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:/">
str = "https://youtu.be/KMBBjzp5hdc"
matches = str.match(/(https:\/\/youtu.be\/)(.+)/)
matches[1]
Outputs:
"https://youtu.be/"