[英]Regex matches in regexpal but not in javascript?
I am trying to find a regex that will work for validating URLs. 我正在尝试找到一个可用于验证URL的正则表达式。 I found this guy:
我找到了这个人:
^(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$
Which worked pretty well when I tested it using regexpal , but when I actually plug it into my javascript it fails to match. 当我使用regexpal测试它时,效果很好,但是当我将其实际插入javascript时,它无法匹配。 Fiddle here.
在这里摆弄。
I am testing against this URL: 我正在针对此URL进行测试:
http://s3.amazonaws.com/SomeShow/Podcasts/HouroneofWhatever234.mp3
Can anyone see why it would match in regexpal, but not when I try to use it in my javascript? 谁能看到为什么它会在正则表达式中匹配,但是当我尝试在JavaScript中使用它时却找不到?
Use a regex literal: 使用正则表达式文字:
/^(http|ftp|https):\/\/[\w-]+...$/
(you also have to escape the slashes to prevent the them to be interpreted as ending regex terminal symbol) (您还必须转义斜线以防止将其解释为正则表达式终端符号)
If you use a string, you have to escape every backslash, because the backslash is the escape characters in strings as well. 如果使用字符串,则必须转义每个反斜杠,因为反斜杠也是字符串中的转义字符。
new RegExp("^(http|ftp|https)://[\\w-]+...$")
In your current expression, "[\\w-]+"
will turn to [w]+
because \\w
is not a valid escape sequence in strings. 在当前表达式中,
"[\\w-]+"
将变为[w]+
因为\\w
在字符串中不是有效的转义序列。
See: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions#Creating_a_Regular_Expression 请参阅: https : //developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Regular_Expressions#Creating_a_Regular_Expression
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.