正则表达式没有按预期工作? [英] Regex is not working as expected?

查看:85
本文介绍了正则表达式没有按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式:

new RegExp("^[a-z 0-9\"\-\`]+$", "ig")

我正在测试一个不是假设的字符串工作:'#vc'

and I'm testing a string which is not suppose to work : '#vc'

但它确实通过了测试:(它不应该())

But it does pass the test : ( and it shouldn't (#))

new RegExp("^[a-z 0-9\"\-\`]+$", "ig").test('#vc') //true

但如果我删除 \ \ - \`,它确实有效(并且测试失败了。)

But if I remove either \" or \- or \`, it does work ( and test fails as it should).

我做错了什么?

我的正则表达式只搜索英文,数字,空格,[],[ - ] [和[`]

My regex simply search for English , numbers , space , ["],[-][ and [`]

推荐答案

如果您使用 RegExp 构造函数,则需要加倍转义,因为有2层转义:在JavaScript字符串文字中转义并在正则表达式语法中转义。

If you use RegExp constructor, you need to double up the escaping, since there are 2 layers of escaping: escaping in JavaScript string literal and escaping in the regex syntax.

但是,在你的情况下,可以写一个正则表达式而不会逃避。

However, in your case, it is possible to write a regex without escaping at all.

在你的情况下,你可以使用 literal RegExp ,你只需要关心正则表达式语法中的转义,并转义出现在正则表达式中的任何 / (从那以后) / 用作文字的分隔符 RegExp

In your case, you can just use literal RegExp, in which you only have to care about escaping in regex syntax, and escaping for any / that appears in the regex (since / is used as delimiter for literal RegExp:

/^[a-z 0-9"\-`]+$/gi

另一种方式是:

/^[a-z 0-9"`-]+$/gi

您无需逃避破折号 - 如果它是字符类中的最后一个。通过这种方式,您无需将自己与所有转义混淆。

You don't need to escape dash - if it is the last in a character class. This way, you don't need to confuse yourself with all the escaping.

或者如果您仍想使用 RegExp 构造函数,你需要加倍转义以在字符串中指定 \

Or if you still want to use RegExp constructor, you need to double up the escape to specify \ in the string:

new RegExp('^[a-z 0-9"\\-`]+$', "ig")

或者只使用在字符类中最后指定 - 的其他版本:

Or just use the other version where - is specified last in the character class:

new RegExp('^[a-z 0-9"`-]+$', "ig")

请注意,我将字符串引用从更改为'避免在字符串中转义。如果由于某种原因,您更喜欢,在文字字符串级别转义

Note that I change the string quote from " to ' to avoid having to escape " in the string. If you for some reason prefers ", escape " at the literal string level:

new RegExp("^[a-z 0-9\"`-]+$", "ig")






至于你现在的正则表达式


As for your current regex

new RegExp("^[a-z 0-9\"\-\`]+$", "ig")

相当于

/^[a-z 0-9"-`]+$/gi

正如您所看到的字符范围`包含,这意味着包含所有ASCII码为0x22到0x60的字符,并且恰好在范围内。

As you can see a character range from " to ` is included, which means all characters with ASCII code from 0x22 to 0x60 are included, and # happens to be in the range.

要检查模式是否符合您的要求,您可以随时调用 source 正则表达式的属性,用于获取正则表达式的源字符串。

To check whether the pattern is what you want, you can always call source property of the regex to obtain the source string of the regex.

这篇关于正则表达式没有按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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