JavaScript正则表达式“没什么可重复的”错误

时间:2021-08-07 20:25:18

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

我在尝试获取令牌代码以进行Minic langauge的词法分析时犯了这个错误!

document.writeln("1,2 3=()9$86,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 !!

我在调试器上发现了最后一行未被捕获的SyntaxError:无效正则表达式:没什么可重复的!

2 个解决方案

#1


6  

You need to escape special characters:

您需要转义特殊字符:

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

See what special characters need to be escaped:

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

#2


3  

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.

你需要转义字符+和*,因为它们在regex中有特殊的含义。我也非常怀疑您是否想要最后一个|—这将向匹配的元素添加空字符串,因此您将得到一个每个元素都有一个字符的数组。

Here's the fixed regex:

这是固定的正则表达式:

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

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

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

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

Demo:

演示:

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

#1


6  

You need to escape special characters:

您需要转义特殊字符:

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

See what special characters need to be escaped:

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

#2


3  

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.

你需要转义字符+和*,因为它们在regex中有特殊的含义。我也非常怀疑您是否想要最后一个|—这将向匹配的元素添加空字符串,因此您将得到一个每个元素都有一个字符的数组。

Here's the fixed regex:

这是固定的正则表达式:

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

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

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

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

Demo:

演示:

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