有没有办法改进这个Javascript正则表达式替换
我正在尝试使用以下Javascript清理windows文件夹路径有没有办法改进这个Javascript正则表达式替换,javascript,regex,Javascript,Regex,我正在尝试使用以下Javascript清理windows文件夹路径 function StandardizeFolderPath(inFolderPath) { var outFolderPath = inFolderPath.replace(/^\s+|\s+$/g, ""); outFolderPath = outFolderPath.replace(/\\\s*/g, "\\"); outFolderPath = outFold
function StandardizeFolderPath(inFolderPath) {
var outFolderPath = inFolderPath.replace(/^\s+|\s+$/g, "");
outFolderPath = outFolderPath.replace(/\\\s*/g, "\\");
outFolderPath = outFolderPath.replace(/\s*\\/g, "\\");
outFolderPath = outFolderPath.replace(/\\{2,}/, "\\");
alert("^" + inFolderPath + "$ " + "^" + outFolderPath + "$");
return outFolderPath;
}
function Test_StandardizeFolderPath() {
StandardizeFolderPath("D:\\hel xo \\");
StandardizeFolderPath("D:\\hello \\ ");
StandardizeFolderPath("D:\\hello \\ \\");
StandardizeFolderPath("D:\\hello \\ mike \\");
StandardizeFolderPath(" D:\\hello \\ jack \\");
StandardizeFolderPath(" D:\\hello Multiple Slashes \\\\");
}
每次更换不包括特定零件:
“\”
替换为“\”
“\”
“\”
替换为一次它完成了任务,但我想知道是否有更好的方法(有解释)您可以合并三个替代者:
function StandardizeFolderPath(inFolderPath) {
return inFolderPath.replace(/^\s+|\s+$/g, "").replace(/(\s*\\\s*)+/g, "\\");
}
以下是/(\s*\\\s*)+/g
的意思:
NODE EXPLANATION
--------------------------------------------------------------------------------
/ start of regex literal
--------------------------------------------------------------------------------
( group \1:
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
\\ '\'
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
)+ end of \1 . The + makes it work for one or
more occurences
--------------------------------------------------------------------------------
/ end of regex literal
--------------------------------------------------------------------------------
g executes more than once
参考资料:
s.replace(/ *(\\)(\\? *)+|^ *| *$/g, "$1")
看起来很有意思
这是一个由空格和反斜杠组成的块,后跟一系列其他反斜杠,或者只保留反斜杠的空格
其他情况是删除起始和结束空格。好吧。。。不是我留下的第一个。你缺少了第四个的
{2,}
。@PeterBoughton不,我没有。这有个+的原因。它还负责处理“\\\\\”或“\\\\”@dystroy。谢谢你的帮助。你能给你的答案加一点解释吗?这样我才能更好地理解。开头“/”和结尾“/g”的意义。还有“()+”是如何工作的。@PranavShah我详细介绍并添加了一些链接,您应该阅读以更好地理解您没有任何4的测试用例。@Dstroy 4th仅使用此语句“D:\\hello\\\\”进行部分测试。中间不可能有空隙。但是你知道在真实的案例中会发生什么,我只是指出了这个与你的规则相关的遗漏。您在下面提供的代码是否也解决了#1 replace的.Y U NO.trim()问题?我认为它目前还不起作用。试试“\\a”
。当然可以修复,但我发现这很难维护和检查。@dystroy:没错,我不知道如何在一次传递的情况下完成所有事情,而不查看任何地方都不支持的零宽度断言。添加了第二个过程。事实上,我认为这些断言在任何浏览器中都不受支持。@dystroy:在吃饭时,我想到使用捕获组可以使它。。。看来它管用。