3

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

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(/,|*|-|+|=|<|>|!|&|,|/));

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

4

2 回答 2

6

您需要转义特殊字符:

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

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

于 2012-05-18T09:57:00.363 回答
4

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 ; }' ]
于 2012-05-18T09:59:11.183 回答