一个正则表达式,它排除以“quot”开头的注释行//&引用;在JavaScript中
我需要找到所有带有字符串“new qx.ui.form.Button”的行,其中不包括以注释“/”开头的行 范例一个正则表达式,它排除以“quot”开头的注释行//&引用;在JavaScript中,javascript,regex,comments,line,Javascript,Regex,Comments,Line,我需要找到所有带有字符串“new qx.ui.form.Button”的行,其中不包括以注释“/”开头的行 范例 line 1:" //btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({" line 2:" btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({" 模式应该只捕捉“第2行”! 注意前导空格 最后,
line 1:" //btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({"
line 2:" btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({"
模式应该只捕捉“第2行”!
注意前导空格
最后,我必须在所有未注释的代码行中用“this.\u getButton”查找并替换“new qx.ui.form.Button”
我试过了
/new.*Button/g
/[^\/]new.*Button/g
还有其他很多都没有成功。在JavaScript中,这有点令人讨厌:
^\s*(?=\S)(?!//)
排除行开头的注释。到目前为止,这是标准的。但是您不能向后看这个模式,因为JS不支持任意长度的向后看,所以您必须匹配和替换超出需要的部分:
^(\s*)(?=\S)(?!//)(.*)(new qx\.ui\.form\.Button)
换成
$1$2this.__getButton
快速PowerShell测试:
PS Home:\> $line1 -replace '^(\s*)(?=\S)(?!//)(.*)(new qx\.ui\.form\.Button)','$1$2this.__getButton'
//btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({
PS Home:\> $line2 -replace '^(\s*)(?=\S)(?!//)(.*)(new qx\.ui\.form\.Button)','$1$2this.__getButton'
btn = this.__getButton(plugin.menuName, plugin.menuIcon).set({
话虽如此,你为什么还要关心评论行中的内容呢?这并不是说它们对程序有任何影响。啊,如果JavaScript有lookbehind。。。那么你所需要的就是
/(?…啊,好吧
这也行:
.replace(/(.*)new\s(qx\.ui\.form\.Button)/g,function(_,m) {
// note that the second set of parentheses aren't needed
// they are there for readability, especially with the \s there.
if( m.indexOf("//") > -1) {
// line is commented, return as-is
// note that this allows comments in an arbitrary position
// to only allow comments at the start of the line (with optional spaces)
// use if(m.match(/^\s*\/\//))
return _;
}
else {
// uncommented! Perform replacement
return m+"this.__getButton";
}
});
Grep使用正则表达式,这将排除任何行开头的所有空格(如果有)加上两个/。
grep-v“^\s*/”Notepad++支持lookbehinds,所以只需使用我给出的第一个正则表达式,并用这个替换匹配项即可