我正在使用Ruby 2.3.0和Rails 4.2.5,我正在关注此文档https://www.sitepoint.com/youtube-rails/ 由于此处有正则表达式用于验证 youtube 网址。我将它复制粘贴到我的rails应用程序中,它在rails console上正常工作
[1] pry(main)> YT_LINK_FORMAT = /^(?:https?:\/\/)?(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=)?([\w-]{10,})/
=> /^(?:https?:\/\/)?(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=)?([\w-]{10,})/
[2] pry(main)> video_url = "https://www.youtube.com/watch?v=aZngT1Eas4w"
=> "https://www.youtube.com/watch?v=aZngT1Eas4w"
[3] pry(main)> uid = video_url.match(YT_LINK_FORMAT)
=> #<MatchData "https://www.youtube.com/watch?v=aZngT1Eas4w" 1:"aZngT1Eas4w">
[4] pry(main)> uid[2]
=> nil
[5] pry(main)> uid[1]
=> "aZngT1Eas4w"
[6] pry(main)> video_url = "https://youtu.be/aZngT1Eas4w"
=> "https://youtu.be/aZngT1Eas4w"
[7] pry(main)> uid = video_url.match(YT_LINK_FORMAT)
=> #<MatchData "https://youtu.be/aZngT1Eas4w" 1:"aZngT1Eas4w">
[8] pry(main)> uid[1]
=> "aZngT1Eas4w"
但是当我运行我的rails应用程序时出现了这个错误
"The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?"
我也尝试使用这个正则表达式
/^(?:https?:\/\/)?(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=)?([\w-]{10,})/
=> /^(?:https?:\/\/)?(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=)?([\w-]{10,})/
但同样的问题仍然存在
答案 0 :(得分:-1)
此正则表达式适用于rails 5
YT_LINK_FORMAT = /(http:\/\/|https:\/\/|)(www.)?(youtu(be\.com|\.be|be\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/