JavaScript 正则表达式“Nothing to repeat”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10650443/
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-10-26 10:33:26  来源:igfitidea点击:

JavaScript regular expression "Nothing to repeat" error

javascriptregex

提问by Mustafa ELnagar

I have this error while trying to get the tokens the code to make the lexical analysis for the Minic langauge !

我在尝试获取标记代码以对 Minic 语言进行词法分析时遇到此错误!

document.writeln("1,2 3=()9,7".split(/,| |=|$|/));

document.writeln("<br>");
document.writeln("int sum ( int x , int y ) { int z = x + y ; }");
document.writeln("<br>");
document.writeln("int sum ( int x , int y ) { int z = x + y ; }".split(/,|*|-|+|=|<|>|!|&|,|/));

I get error on the debugger for the last line Uncaught SyntaxError: Invalid regular expression: Nothing to repeat !!

我在调试器的最后一行出现错误 Uncaught SyntaxError: Invalid regular expression: Nothing to repeat !!

回答by antyrat

You need to escape special characters:

您需要转义特殊字符:

/,|\*|-|\+|=|<|>|!|&|,|/

Seewhat special characters need to be escaped:

查看哪些特殊字符需要转义:

回答by ThiefMaster

You need to escape the characters +and *since they have a special meaning in regexes. I also highly doubt that you wanted the last |- this adds the empty string to the matched elements and thus you get an array with one char per element.

您需要对字符进行转义+*因为它们在正则表达式中具有特殊含义。我也非常怀疑您是否想要最后一个|- 这会将空字符串添加到匹配的元素中,因此您会得到一个每个元素一个字符的数组。

Here's the fixed regex:

这是固定的正则表达式:

/\*|-|\+|=|<|>|!|&|,/

However, you can make the it much more readable and maybe even faster by using a character class:

但是,您可以通过使用字符类使其更具可读性,甚至可能更快:

/[-,*+=<>!&]/

Demo:

演示:

js> "int sum ( int x , int y ) { int z = x + y ; }".split(/[-,*+=<>!&]/);
[ 'int sum ( int x ',
  ' int y ) { int z ',
  ' x ',
  ' y ; }' ]