【发布时间】:2020-01-11 09:23:27
【问题描述】:
我有一个正则表达式问题。我有这个正则表达式:
/(https|http):\/\/(kwagmire)\.(com)\/(embed)\/([a-zA-Z0-9]+)/i
这在 https://regexr.com 上正确捕获,但在 Ruby on Rails 上任何带有
的内容http://kwagmire.com/embed/1QgJVmCam
返回一个真实的值,我认为是因为它设置了我不想要的 global 标志。
我尝试了match 和scan,但如果看到链接,仍然会返回一个真实值。我只是想让它具体一点。
https://kwagmire.com/embed/1QgJVmCam < I want to return success this one is ok when testing on console
http://kwagmire.com/embed/1QgJVmCam < I want to return success also this on returns good
https.evil.com/http://jsitor.com/embed/1QgJVmCam < I want to return fail or nil, this one passes returns all match
facebook.com < I want to return fail or nil this one is good because it's failing
https://google.com < I want to return fail or nil also this good failed
www.twitter.com < I want to return fail or nil
http://kwagmire.com/embed/1QgJVmCam/?onload(alert('asdfadsf')) < I want to return fail or nil, this one also is failing, good
http://kwagmire.com/embed/1QgJVmCam/ onload(alert('asdfadsf')) < I want to return fail or nil, this one returns match too but should fail
http://kwagmire.com/embed/1QgJVmCam/?onload(alert('asdfadsf')) < I want to return fail or nil, this one returns match too, this should fail
基本上我想要这个https://kwagmire.com/embed/1QgJVmCam 其他的都应该返回 nil 或 false。有没有不循环的简单方法?我认为这个解决方案是删除全局标志或g,但你有这个选项吗?如果是这样,我为什么要这样做?
查看/之后的i
/(https|http):\/\/(jsitor)\.(com)\/(embed)\/([a-zA-Z0-9]+)/i.match("http://jsitor.com/embed/1QgJVmCam/ onload(alert('asdfadsf'))")
然后返回,但这应该会失败
#<MatchData "http://jsitor.com/embed/1QgJVmCam" 1:"http" 2:"jsitor" 3:"com" 4:"embed" 5:"1QgJVmCam">
【问题讨论】:
-
您能更具体地说明您想要实现的目标吗?你能提供一些你想要匹配和不应该匹配的链接的测试链接吗?
-
@allenbrkn 检查
<之前的文本我编辑了它 -
对于它的价值,这不是关于 Rails 的问题。这是一个关于纯 Ruby 的问题。
-
您需要根据您想要实现的目标来陈述您的问题,不参考正则表达式。也就是说,您有许多要测试的字符串。只有一个通过了测试。测试是什么?这就是您需要构建问题的方式。完成后,您可以展示您尝试过的正则表达式,并解释它为什么不起作用。最后,别再猜测为什么正则表达式不起作用了。