字符类中的Javascript正则表达式无效范围 [英] Javascript regex invalid range in character class

查看:57
本文介绍了字符类中的Javascript正则表达式无效范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用从regexlib获得的regex模式来验证相对URL.在他们的网站上,您可以测试模式,以确保其符合您的需求.在我的网站上,一切工作正常,一旦我在我的模式中使用该模式,我就会收到错误消息:

I'm using a regex pattern that I got from regexlib to validate relative urls. On their site you can test the pattern to make sure it fits your needs. Everything works great on their site, as soon as I use the pattern in mine I get the error message:

字符类中的无效范围

Invalid range in character class

我知道此错误通常意味着连字符被错误地用来表示范围,并且不能正确转义.但是在这种情况下,由于它可以在他们的网站上运行,我很困惑为什么它不能在我的网站上运行.

I know that this error usually means that a hyphen is mistakenly being used to represent a range and is not properly escaped. But in this case since it works on their site I'm confused why it's not working on mine.

var urlRegex = new RegExp('^(?:(?:\.\./)|/)?(?:\w(?:[\w`~!$=;\-\+\.\^\(\)\|\{\}\[\]]|(?:%\d\d))*\w?)?(?:/\w(?:[\w`~!$=;\-\+\.\^\(\)\|\{\}\[\]]|(?:%\d\d))*\w?)*(?:\?[^#]+)?(?:#[a-z0-9]\w*)?$', 'g');

注意:如果要从其站点测试正则表达式(使用上面的链接),请确保将 Regex Engine 下拉菜单更改为 Client-side Engine 引擎下拉至 Javascript .

NOTE: If you're going to test the regex from their site (using the link above) be sure to change the Regex Engine dropdown to Client-side Engine and the Engine dropdown to Javascript.

推荐答案

-放在字符类的开始使用两个反斜杠字符串

Either put - at the end or beginning of the character class or use two backslashes to do a regex escape within string

由于您使用的是字符串,因此每个特殊字符都需要使用两个反斜杠.

since you are using string you need to use two backslashes for each special characters..

注意

在SO上查看答案,其中说明了何时使用单反斜线或双反斜线可转义特殊字符

Check out this answer on SO which explains when to use single or double backslashes to escape special characters

这篇关于字符类中的Javascript正则表达式无效范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆