Reputation: 492
I have this error while trying to get the tokens the code to make the lexical analysis for the 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 !!
Upvotes: 3
Views: 18149
Reputation: 318488
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 ; }' ]
Upvotes: 4