我是正则表达式的初学者。
我一直在使用 regex101 尝试找出一种方法来捕获声明中的变量标识符。基本上 var x = 1;
中的 x
而不是 x = x + 1
。
我正在使用 PrismJS 尝试突出显示我的代码,它不支持非捕获 (?:)
并且它捕获每个部分匹配,但它可以选择忽略第一个括号以模仿“向后看”功能。
我使用以下文本进行测试:
var a = 1,
b=2,
c = 3;
var d = 5;
var x, y = 3,
z;
var x = 1,
z = 1.23E4, //comment
w = +Infinity,
u = NaN,
t = 0x6F, //hexidecimal
r = 0o37; //octadecimal
到目前为止,我只能想出一个技巧正则表达式:
/(var *| *,\n* *)(\w+)(?= *=| *,| *;)/g
// not captured ^ not captured
// captured
第一个括号将被忽略并且不会被捕获以模仿 lookbehind。 我无法在第一个 |
之后使用 var
括号。
当然,它也会捕获我不想要的:
,
a =
请帮忙。有太多的限制,或者可能只是我太笨了,我无法构建一个有效的正则表达式。
最佳答案
好的,经过几个小时的修改,这是一个初步版本!
正则表达式是 /(var\s*|(?!^),\s*|(?!^),\s*\/\/*.*?\n\s*)(\w+)/gm
.
解释:
(
var\s* // Matches "var" + whitespace (always a declaration)
| (?!^),\s* // Matches comma + whitespace
| (?!^),\s*\/\/ *.*?\n\s* // Matches comma + // comment + newline(s)
)
(\w+) // The identifier itself
顺便说一下,这也适用于 for 循环等,这要归功于带有 var
的情况 1。
案例 3 比较时髦;它不适用于所有情况,但捕获了很多情况。它会查找逗号(重要)后面有空格的内联注释。
下面是一个演示,我们在其中突出显示了变量名称。请注意,这不会捕获整个赋值,但您可以添加一些可选内容来突出显示整个内容或仅突出显示值,而不是仅显示标识符。
function highlight (src) {
var regex = /(var\s*|(?!^),\s*|(?!^),\s*\/\/ *.*?\n\s*)(\w+)/gm;
return src.replace(regex, "$1<span class='hl'>$2</span>");
}
window.onload = function () {
var src = document.querySelector("pre").textContent;
document.querySelector("pre").innerHTML = highlight(src);
};
body {
line-height: 20px;
}
.hl {
background: rgba(90, 255, 90, 0.2);
border-radius: 3px;
padding: 0 3px;
border: 1px solid #444;
cursor: default;
}
.hl:hover {
background: rgba(90, 255, 90, 0.7);
}
<pre>
// everything below should highlight
var a = 1,
b = 2,
c = 3;
var d = 5;
var x, y = 3,
z;
z; // this shouldn't highlight
var me = 9, z3 = 10; // these two should highlight
x = x + 1; // this shouldn't
for (var i = 0; i < 5) {} // `i` here should highlight
// these should highlight
var x,y;
var m=19, zzz=12;
// this shouldn't
zzz = 15;
// and all of these should highlight.
var x = 1,
z = 1.23E4, //comment
someName = +Infinity,
u = NaN,
t = 0x6F, //hexidecimal
r = 0o37; //octadecimal
// these should both highlight
var x, // variable
y;
// these should be highlighted too
var x, //variable
y;
// and this shouldn't
,
a = 4;
</pre>
关于javascript - JS代码高亮正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022163/