1

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?

2
  • 4
    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. Commented Dec 6, 2012 at 2:55
  • that worked great, thank you. If you put it as an answer I will certainly accept. Commented Dec 6, 2012 at 3:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.