Javascript + Regex = 没有重复错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6288181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:07:41  来源:igfitidea点击:

Javascript + Regex = Nothing to repeat error?

javascriptregexmatch

提问by esqew

I'm new to Regex and I'm trying to work it into one of my new projects to see if I can learn it and add it to my repittheitroade of skills. However, I'm hitting a roadblock here.

我是 Regex 的新手,我正在尝试将它应用到我的一个新项目中,看看我是否可以学习它并将其添加到我的技能库中。但是,我在这里遇到了障碍。

I'm trying to see if the user's input has illegal characters in it by using the .searchfunction as so:

我试图通过使用该.search函数来查看用户的输入中是否包含非法字符:

if (name.search("[\[\]\?\*\+\|\{\}\\(\)\@\.\n\r]") != -1) {
    ...
}

However, when I try to execute the function this line is contained it, it throws the following error for that specific line:

但是,当我尝试执行该行包含的函数时,它会针对该特定行引发以下错误:

Uncaught SyntaxError: Invalid regular expression: /[[]?*+|{}\()@.

]/: Nothing to repeat

I can't for the life of me see what's wrong with my code. Can anyone point me in the right direction?

我一辈子都看不到我的代码有什么问题。任何人都可以指出我正确的方向吗?

回答by andrewdski

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

您需要将用于转义正则表达式特殊字符的反斜杠加倍。但是,正如@Bohemian 指出的那样,大多数反斜杠都不需要。不幸的是,他的答案与您的问题存在相同的问题。你真正想要的是:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

反斜杠由读取字符串的代码解释,而不是传递给正则表达式解析器。你要:

"[\[\]?*+|{}\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

注意四重反斜杠。那肯定是需要的。传递给正则表达式编译器的字符串与@Bohemian 的字符串相同,并且可以正常工作。

回答by NobodyMan

Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:

基于@Bohemian,我认为最简单的方法是使用正则表达式文字,例如:

if (name.search(/[\[\]?*+|{}\()@.\n\r]/) != -1) {
    // ... stuff ...
}

Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).

正则表达式文字很好,因为您不必转义转义字符,并且一些 IDE 会突出显示无效的正则表达式(对我来说非常有帮助,因为我经常把它们搞砸)。

回答by Bohemian

Firstly, in a character class [...]mostcharacters don't need escaping - they are just literals.

首先,在字符类中,[...]大多数字符不需要转义——它们只是文字。

So, your regex should be:

所以,你的正则表达式应该是:

"[\[\]?*+|{}\()@.\n\r]"

This compiles for me.

这为我编译。