Mustafa ELnagar
Mustafa ELnagar

Reputation: 492

JavaScript regular expression "Nothing to repeat" error

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

Answers (2)

ThiefMaster
ThiefMaster

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

antyrat
antyrat

Reputation: 27765

You need to escape special characters:

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

See what special characters need to be escaped:

Upvotes: 6

Related Questions