ruby - 匹配返回另一个输出
问题描述
插入输入值“https://youtu.be/KMBBjzp5hdc”后,代码返回输出值“https://youtu.be/”
str = gets.chomp.to_s
puts /.*[=\/]/.match(str)
我不明白为什么正如我所期望的那样 https://
谢谢指教!
解决方案
[...] 代码返回输出值
"https://youtu.be/"
[...] 我不明白为什么如我所料https:/
您的正则表达式/.*[=\/]/
匹配:
.*
零个或多个字符[=\/]
后跟一个=
或/
字符
在您的示例字符串中,有 3 个以/
字符结尾的候选项:(并且没有以 结尾=
)
https:/
https://
https://youtu.be/
重复喜欢默认*
是贪婪的,即它匹配尽可能多的字符。从上面的 3 个选项中,它匹配最长的一个,即https://youtu.be/
.
您可以附加 a?
以使重复变得惰性,从而产生最短匹配:
"https://youtu.be/KMBBjzp5hdc".match(/.*?[=\/]/)
#=> #<MatchData "https:/">
推荐阅读
- javascript - 更改 d3.format 用于“g”类型的表示法
- java - JavaFX 不使用类中的线程
- arduino - 使用 Eclipse Photon CDT Core Builder 编译 avr c++ lib
- html - Bootstrap 4.0轮播不工作
- android - 具有不同布局的可扩展 recyclerview 适配器
- javascript - 在 precommit 中运行 ESLint 不会因警告而停止
- python - 从其他 m 行中减去 m 行数据帧
- java - 如何用 Spring 调用 4 单元测试替换常用的新关键字?
- angular - 标识符是指角度中的私有成员
- php - NGINX:connect() 到 unix:/var/run/php7.2-fpm.sock 失败(2:没有这样的文件或目录)