javascript - 变量和数字的正则表达式匹配

标签 javascript regex

我正在尝试匹配 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/

相关文章:

javascript - 用于 unix 密码哈希的 node.js DES 加密不像 mkpasswd 那样工作

浏览器之间的javascript鼠标事件兼容性问题

javascript - jQuery 限制文本函数

javascript - 时间字符串到日期对象转换js angularJS

javascript - 正则表达式在 IE 11 中抛出错误

javascript - 正则表达式如何验证 URL

regex - Oracle 在多行字符串中进行条件搜索

javascript - Ember js 2.0 将计算属性从 Controller 传递到组件

javascript - 放大或缩小时对齐列表项

javascript - 仅控制多个电子邮件域的正则表达式