我正在尝试匹配 JavaScript 字符串中的变量和数字(周围带有 span 标签的匹配)。
我遇到了 x1、c2 等形式的变量问题。我的代码最初看起来像这样
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
这导致 [a-zA-Z]+\d+ 形式的变量无法正确匹配,因为它们已被数字标签替换。
我一直在尝试使用前瞻和诸如 [^A-Za-z]?\d+
之类的数字来进行一些操作,但一直无法找到一种好的方法这个。
我知道我可以匹配标签,但想要一个更优雅的解决方案。
我是否缺少一个明显的逻辑解决方案,或者是否有人有一个我不知道的正则表达式运算符来应对这种情况?
最佳答案
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
关于javascript - 变量和数字的正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13736199/