Ben McCormick
Ben McCormick

Reputation: 25718

Regex matching for variables and numbers

I'm trying to match variables and numbers in a javascript string (surrounding matches with span tags).

I'm having issues with variables in the form x1, c2 etc. My code originally looked like this

output = output.replace(/\d+/g,"<span class=\"number\">$&</span>");
output = output.replace(/\)/g,"<span class=\"function\">$&</span>");
output = output.replace(/[a-zA-Z]+\d*/g,returnTextValue); 
//returnTextValue is a function checking whether the string is a variable or plain text
//and highlighting accordingly

This caused variables in the form [a-zA-Z]+\d+ to not get matched correctly, because they had already been replaced with the number tag.

I've been trying a few things using lookaheads and stuff like [^A-Za-z]?\d+ for the numbers, but have not been able to find a good way of doing this.

I know I could match the tags, but would like a more elegant solution.

Am I missing an obvious logical solution, or does somebody have a regex operator I don't know for this situation?

Upvotes: 1

Views: 134

Answers (1)

Bill the Lizard
Bill the Lizard

Reputation: 405685

Is the \d+ in the first rule supposed to match isolated numbers? Add boundaries \b\d+\b, then it won't match the a2 type. – Michael Berkowski Dec 6 at 2:55

Upvotes: 1

Related Questions