0

次の Javascript を使用して Windows フォルダー パスをクリーンアップしようとしています。




    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 \\\\");
    }



各置換は特定の部分を行います:

  1. 前後のスペースを削除
  2. "\ "いずれかを置き換えます"\"
  3. 置き換えます" \"
  4. 複数出現する"\"を 1 つに置き換えます。

それは仕事を終わらせますが、もっと良い方法があるかどうか知りたいです(説明付き)

4

2 に答える 2

2

3 つの置換をマージできます。

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

参考文献:

于 2013-09-18T17:16:47.707 に答える
0

単一の正規表現

s.replace(/ *(\\)(\\? *)+|^ *| *$/g, "$1")

トリックを行うようです。

アイデアは、スペースで構成されたブロックの後にバックスラッシュが続き、その後に一連の他のバックスラッシュまたはバックスラッシュのみを保持したいスペースが続くというものです。

他のケースは、最初と最後のスペースを削除するためのものです。

于 2013-09-18T17:39:32.483 に答える