首页 > 解决方案 > 匹配返回另一个输出

问题描述

插入输入值“https://youtu.be/KMBBjzp5hdc”后,代码返回输出值“https://youtu.be/”

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

我不明白为什么正如我所期望的那样 https://

谢谢指教!

标签: ruby

解决方案


[...] 代码返回输出值"https://youtu.be/"[...] 我不明白为什么如我所料https:/

您的正则表达式/.*[=\/]/匹配:

  • .*零个或多个字符
  • [=\/]后跟一个=/字符

在您的示例字符串中,有 3 个以/字符结尾的候选项:(并且没有以 结尾=

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

重复喜欢默认*贪婪的,即它匹配尽可能多的字符。从上面的 3 个选项中,它匹配最长的一个,即https://youtu.be/.

您可以附加 a?以使重复变得惰性,从而产生最短匹配:

"https://youtu.be/KMBBjzp5hdc".match(/.*?[=\/]/)
#=> #<MatchData "https:/">

推荐阅读