コマンドラインパラメータを含む文字列をC#のstring []に分割します

StackOverflow https://stackoverflow.com/questions/298830

  •  08-07-2019
  •  | 
  •  

質問

別の実行可能ファイルに渡されるコマンドラインパラメータを含む単一の文字列があり、コマンドでコマンドが指定された場合のC#と同じ方法で、個々のパラメータを含むstring []を抽出する必要があります-ライン。 string []は、リフレクションを介して別のアセンブリエントリポイントを実行するときに使用されます。

これに標準機能はありますか?または、パラメータを正しく分割するための好ましい方法(正規表現?)はありますか? 「<!> quot;」を処理する必要がありますスペースを正しく含む可能性のある区切り文字列なので、 ''で分割することはできません。

文字列の例:

string parameterString = @"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam foo";

結果の例:

string[] parameterArray = new string[] { 
  @"/src:C:\tmp\Some Folder\Sub Folder",
  @"/users:abcdefg@hijkl.com",
  @"tasks:SomeTask,Some Other Task",
  @"-someParam",
  @"foo"
};

コマンドライン解析ライブラリは必要ありません。生成されるString []を取得する方法です。

更新:予想される結果を、C#によって実際に生成されるものと一致するように変更する必要がありました(分割文字列の余分な<!> quot;を削除しました)

役に立ちましたか?

解決

goodに加えて Earwicker による純粋なマネージドソリューション、完全性のために、Windowsも提供する価値があるかもしれません文字列を文字列の配列に分割するための CommandLineToArgvW 関数:

LPWSTR *CommandLineToArgvW(
    LPCWSTR lpCmdLine, int *pNumArgs);
     

Unicodeコマンドライン文字列を解析します   ポインタの配列を返します   コマンドライン引数と一緒に   ある意味で、そのような引数の数   それは標準Cに似ています   ランタイムargvおよびargc値。

このAPIをC#から呼び出し、マネージコードで結果の文字列配列を展開する例は、"CommandLineToArgvW()APIを使用してコマンドライン文字列をArgs []に変換。" (http://intellitect.com/converting-command-line-string-to-args-using-commandlinetoargvw-api/)以下は、同じコードのやや単純なバージョンです。

[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW(
    [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);

public static string[] CommandLineToArgs(string commandLine)
{
    int argc;
    var argv = CommandLineToArgvW(commandLine, out argc);        
    if (argv == IntPtr.Zero)
        throw new System.ComponentModel.Win32Exception();
    try
    {
        var args = new string[argc];
        for (var i = 0; i < args.Length; i++)
        {
            var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);
            args[i] = Marshal.PtrToStringUni(p);
        }

        return args;
    }
    finally
    {
        Marshal.FreeHGlobal(argv);
    }
}

他のヒント

各文字を調べる関数に基づいて文字列を分割する関数がないことは私を悩ませます。もしあれば、次のように書くことができます:

    public static IEnumerable<string> SplitCommandLine(string commandLine)
    {
        bool inQuotes = false;

        return commandLine.Split(c =>
                                 {
                                     if (c == '\"')
                                         inQuotes = !inQuotes;

                                     return !inQuotes && c == ' ';
                                 })
                          .Select(arg => arg.Trim().TrimMatchingQuotes('\"'))
                          .Where(arg => !string.IsNullOrEmpty(arg));
    }

それを書きましたが、必要な拡張メソッドを書きませんか。さて、あなたは私にそれを話しました...

まず、指定された文字で文字列を分割するかどうかを決定する必要がある関数を使用するSplitの独自バージョン:

    public static IEnumerable<string> Split(this string str, 
                                            Func<char, bool> controller)
    {
        int nextPiece = 0;

        for (int c = 0; c < str.Length; c++)
        {
            if (controller(str[c]))
            {
                yield return str.Substring(nextPiece, c - nextPiece);
                nextPiece = c + 1;
            }
        }

        yield return str.Substring(nextPiece);
    }

状況に応じていくつかの空の文字列が生成される場合がありますが、その情報は他の場合に役立つ可能性があるため、この関数の空のエントリを削除しません。

二番目に(そしてもっと日常的に)文字列の最初と最後から引用符の一致するペアをトリムする小さなヘルパー。標準のトリム方法よりも面倒です-各端から1文字だけをトリムし、片端だけからはトリムしません:

    public static string TrimMatchingQuotes(this string input, char quote)
    {
        if ((input.Length >= 2) && 
            (input[0] == quote) && (input[input.Length - 1] == quote))
            return input.Substring(1, input.Length - 2);

        return input;
    }

そして、いくつかのテストも必要になると思います。さて、大丈夫。しかし、これは絶対に最後のものでなければなりません!最初に、分割の結果を予想される配列の内容と比較するヘルパー関数:

    public static void Test(string cmdLine, params string[] args)
    {
        string[] split = SplitCommandLine(cmdLine).ToArray();

        Debug.Assert(split.Length == args.Length);

        for (int n = 0; n < split.Length; n++)
            Debug.Assert(split[n] == args[n]);
    }

その後、次のようなテストを作成できます。

        Test("");
        Test("a", "a");
        Test(" abc ", "abc");
        Test("a b ", "a", "b");
        Test("a b \"c d\"", "a", "b", "c d");

要件のテストは次のとおりです。

        Test(@"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam",
             @"/src:""C:\tmp\Some Folder\Sub Folder""", @"/users:""abcdefg@hijkl.com""", @"tasks:""SomeTask,Some Other Task""", @"-someParam");

実装には、理にかなっている場合は引数を囲む引用符を削除するという追加機能があります(TrimMatchingQuotes関数のおかげです)。これは通常のコマンドライン解釈の一部だと思います。

Windowsコマンドラインパーサーは、前に閉じられていない引用符がない限り、スペースで分割するように動作します。パーサーを自分で作成することをお勧めします。多分このようなもの:

    static string[] ParseArguments(string commandLine)
    {
        char[] parmChars = commandLine.ToCharArray();
        bool inQuote = false;
        for (int index = 0; index < parmChars.Length; index++)
        {
            if (parmChars[index] == '"')
                inQuote = !inQuote;
            if (!inQuote && parmChars[index] == ' ')
                parmChars[index] = '\n';
        }
        return (new string(parmChars)).Split('\n');
    }

ジェフリー・L・ホイットレッジからの回答とそれを少し強化しました。

一重引用符と二重引用符の両方をサポートするようになりました。他の型付き引用符を使用することにより、パラメーター自体で引用符を使用できます。

引数情報から引用符が削除されるため、引数から引用符も削除されます。

    public static string[] SplitArguments(string commandLine)
    {
        var parmChars = commandLine.ToCharArray();
        var inSingleQuote = false;
        var inDoubleQuote = false;
        for (var index = 0; index < parmChars.Length; index++)
        {
            if (parmChars[index] == '"' && !inSingleQuote)
            {
                inDoubleQuote = !inDoubleQuote;
                parmChars[index] = '\n';
            }
            if (parmChars[index] == '\'' && !inDoubleQuote)
            {
                inSingleQuote = !inSingleQuote;
                parmChars[index] = '\n';
            }
            if (!inSingleQuote && !inDoubleQuote && parmChars[index] == ' ')
                parmChars[index] = '\n';
        }
        return (new string(parmChars)).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
    }

管理された純粋な Earwicker によるソリューションは、次のような引数の処理に失敗しました。

Test("\"He whispered to her \\\"I love you\\\".\"", "He whispered to her \"I love you\".");

3つの要素が返されました:

"He whispered to her \"I
love
you\"."

ここで、<!> quot; quoted \ <!> quot; escape \ <!> quot;をサポートするための修正があります。 quote <!> quot;:

public static IEnumerable<string> SplitCommandLine(string commandLine)
{
    bool inQuotes = false;
    bool isEscaping = false;

    return commandLine.Split(c => {
        if (c == '\\' && !isEscaping) { isEscaping = true; return false; }

        if (c == '\"' && !isEscaping)
            inQuotes = !inQuotes;

        isEscaping = false;

        return !inQuotes && Char.IsWhiteSpace(c)/*c == ' '*/;
        })
        .Select(arg => arg.Trim().TrimMatchingQuotes('\"').Replace("\\\"", "\""))
        .Where(arg => !string.IsNullOrEmpty(arg));
}

2つの追加ケースでテスト済み:

Test("\"C:\\Program Files\"", "C:\\Program Files");
Test("\"He whispered to her \\\"I love you\\\".\"", "He whispered to her \"I love you\".");

また、受け入れられた回答 Atif Aziz CommandLineToArgvW も失敗しました。 4つの要素を返しました:

He whispered to her \ 
I 
love 
you". 

これは、将来そのような解決策を探している人に役立つことを願っています。

イテレータが好きで、最近では LINQ により、IEnumerable<String>を配列のように簡単に使用できます文字列ですので、 Jeffrey L Whitledgeの答えは(stringへの拡張方法として):

public static IEnumerable<string> ParseArguments(this string commandLine)
{
    if (string.IsNullOrWhiteSpace(commandLine))
        yield break;

    var sb = new StringBuilder();
    bool inQuote = false;
    foreach (char c in commandLine) {
        if (c == '"' && !inQuote) {
            inQuote = true;
            continue;
        }

        if (c != '"' && !(char.IsWhiteSpace(c) && !inQuote)) {
            sb.Append(c);
            continue;
        }

        if (sb.Length > 0) {
            var result = sb.ToString();
            sb.Clear();
            inQuote = false;
            yield return result;
        }
    }

    if (sb.Length > 0)
        yield return sb.ToString();
}

このコードプロジェクトの記事は、過去。これはかなりのコードですが、動作する可能性があります。

この MSDNの記事は、私が見つけることができる唯一のものですC#がコマンドライン引数を解析する方法を説明します。

あなたの質問で正規表現を求めましたが、私は彼らの大ファンであり、ユーザーであるため、あなたと同じ議論を分割する必要があるとき、私はグーグルで簡単な解決策を見つけずに独自の正規表現を書きました。私は短い解決策が好きなので、私はそれを作りました。ここにそれがあります:

            var re = @"\G(""((""""|[^""])+)""|(\S+)) *";
            var ms = Regex.Matches(CmdLine, re);
            var list = ms.Cast<Match>()
                         .Select(m => Regex.Replace(
                             m.Groups[2].Success
                                 ? m.Groups[2].Value
                                 : m.Groups[4].Value, @"""""", @"""")).ToArray();

引用符内の空白と引用符を処理し、囲まれた<!> quot; <!> quot;を変換します。 <!> quot;に。コードを自由に使用してください!

純粋に管理されたソリューションが役立つ場合があります。 <!> quot;問題<!> quotが多すぎます。 WINAPI関数に関するコメント。他のプラットフォームでは使用できません。これは、明確に定義された動作(必要に応じて変更できます)を持つ私のコードです。

.NET / Windowsがそのstring[] argsパラメーターを提供するときと同じように実行する必要があり、多くの<!> quot; interesting <!> quot;と比較しました。値。

これは、入力文字列から各文字を取得して現在の状態を解釈し、出力と新しい状態を生成する古典的な状態マシンの実装です。状態は変数escapeinQuotehadQuoteおよびprevChで定義され、出力はcurrentArgおよびargsで収集されます。

実際のコマンドプロンプト(Windows 7)での実験で発見したいくつかの専門分野:\\\を生成し、\""を生成し、""は引用範囲内で<=を生成します>。

^文字も魔法のようです。二重にしないと常に消えます。それ以外の場合、実際のコマンドラインには影響しません。私はこの動作にパターンを見つけていないため、私の実装ではこれをサポートしていません。誰かがそれについてもっと知っているかもしれません。

このパターンに合わないものは次のコマンドです:

cmd /c "argdump.exe "a b c""

cmdコマンドは、外側の引用符をキャッチし、残りをそのまま取得するようです。これには特別な魔法のソースが必要です。

メソッドのベンチマークは行っていませんが、かなり高速だと考えています。 Regexは使用せず、文字列の連結も行いませんが、代わりにStringBuilderを使用して引数の文字を収集し、リストに入れます。

/// <summary>
/// Reads command line arguments from a single string.
/// </summary>
/// <param name="argsString">The string that contains the entire command line.</param>
/// <returns>An array of the parsed arguments.</returns>
public string[] ReadArgs(string argsString)
{
    // Collects the split argument strings
    List<string> args = new List<string>();
    // Builds the current argument
    var currentArg = new StringBuilder();
    // Indicates whether the last character was a backslash escape character
    bool escape = false;
    // Indicates whether we're in a quoted range
    bool inQuote = false;
    // Indicates whether there were quotes in the current arguments
    bool hadQuote = false;
    // Remembers the previous character
    char prevCh = '\0';
    // Iterate all characters from the input string
    for (int i = 0; i < argsString.Length; i++)
    {
        char ch = argsString[i];
        if (ch == '\\' && !escape)
        {
            // Beginning of a backslash-escape sequence
            escape = true;
        }
        else if (ch == '\\' && escape)
        {
            // Double backslash, keep one
            currentArg.Append(ch);
            escape = false;
        }
        else if (ch == '"' && !escape)
        {
            // Toggle quoted range
            inQuote = !inQuote;
            hadQuote = true;
            if (inQuote && prevCh == '"')
            {
                // Doubled quote within a quoted range is like escaping
                currentArg.Append(ch);
            }
        }
        else if (ch == '"' && escape)
        {
            // Backslash-escaped quote, keep it
            currentArg.Append(ch);
            escape = false;
        }
        else if (char.IsWhiteSpace(ch) && !inQuote)
        {
            if (escape)
            {
                // Add pending escape char
                currentArg.Append('\\');
                escape = false;
            }
            // Accept empty arguments only if they are quoted
            if (currentArg.Length > 0 || hadQuote)
            {
                args.Add(currentArg.ToString());
            }
            // Reset for next argument
            currentArg.Clear();
            hadQuote = false;
        }
        else
        {
            if (escape)
            {
                // Add pending escape char
                currentArg.Append('\\');
                escape = false;
            }
            // Copy character from input, no special meaning
            currentArg.Append(ch);
        }
        prevCh = ch;
    }
    // Save last argument
    if (currentArg.Length > 0 || hadQuote)
    {
        args.Add(currentArg.ToString());
    }
    return args.ToArray();
}

使用:

public static string[] SplitArguments(string args) {
    char[] parmChars = args.ToCharArray();
    bool inSingleQuote = false;
    bool inDoubleQuote = false;
    bool escaped = false;
    bool lastSplitted = false;
    bool justSplitted = false;
    bool lastQuoted = false;
    bool justQuoted = false;

    int i, j;

    for(i=0, j=0; i<parmChars.Length; i++, j++) {
        parmChars[j] = parmChars[i];

        if(!escaped) {
            if(parmChars[i] == '^') {
                escaped = true;
                j--;
            } else if(parmChars[i] == '"' && !inSingleQuote) {
                inDoubleQuote = !inDoubleQuote;
                parmChars[j] = '\n';
                justSplitted = true;
                justQuoted = true;
            } else if(parmChars[i] == '\'' && !inDoubleQuote) {
                inSingleQuote = !inSingleQuote;
                parmChars[j] = '\n';
                justSplitted = true;
                justQuoted = true;
            } else if(!inSingleQuote && !inDoubleQuote && parmChars[i] == ' ') {
                parmChars[j] = '\n';
                justSplitted = true;
            }

            if(justSplitted && lastSplitted && (!lastQuoted || !justQuoted))
                j--;

            lastSplitted = justSplitted;
            justSplitted = false;

            lastQuoted = justQuoted;
            justQuoted = false;
        } else {
            escaped = false;
        }
    }

    if(lastQuoted)
        j--;

    return (new string(parmChars, 0, j)).Split(new[] { '\n' });
}

Vapour in the Alley の回答に基づいて、これは^エスケープもサポートしています。

例:

  • これはテストです
    • これ
    • a
    • テスト
  • この<!> quot;は<!> quot;テスト
    • これ
    • テスト
  • この^ <!> quot;はa ^ <!> quot;テスト
    • これ
    • <!> quot; is
    • a <!> quot;
    • テスト
  • this <!> quot; <!> quot; <!> quot;は^^テスト<!> quot;
    • これ
    • <!>#8203;
    • は^テストです

複数のスペースもサポートします(スペースのブロックごとに1回だけ引数を分割します)。

ああ。それはすべて...エフ。 これは MicrosoftからC#for .NET Coreで、おそらくWindowsのみ、クロスプラットフォームであるかもしれませんが、MITはライセンスを取得しています。

tidbits、メソッド宣言、注目すべきコメントを選択してください。

internal static unsafe string[] InternalCreateCommandLine(bool includeArg0)
private static unsafe int SegmentCommandLine(char * pCmdLine, string[] argArray, bool includeArg0)
private static unsafe int ScanArgument0(ref char* psrc, char[] arg)
private static unsafe int ScanArgument(ref char* psrc, ref bool inquote, char[] arg)

-

// First, parse the program name (argv[0]). Argv[0] is parsed under special rules. Anything up to 
// the first whitespace outside a quoted subtring is accepted. Backslashes are treated as normal 
// characters.

-

// Rules: 2N backslashes + " ==> N backslashes and begin/end quote
//      2N+1 backslashes + " ==> N backslashes + literal "
//         N backslashes     ==> N backslashes

これは、.NET Frameworkから.NET Coreに移植されたコードで、MSVC CライブラリまたはCommandLineToArgvWのいずれかであると想定しています。

これは、正規表現を使用していくつかのシェナンガンを処理し、引数のゼロビットを無視するという中途半端な試みです。それは少しウィザードです。

private static readonly Regex RxWinArgs
  = new Regex("([^\\s\"]+\"|((?<=\\s|^)(?!\"\"(?!\"))\")+)(\"\"|.*?)*\"[^\\s\"]*|[^\\s]+",
    RegexOptions.Compiled
    | RegexOptions.Singleline
    | RegexOptions.ExplicitCapture
    | RegexOptions.CultureInvariant);

internal static IEnumerable<string> ParseArgumentsWindows(string args) {
  var match = RxWinArgs.Match(args);

  while (match.Success) {
    yield return match.Value;
    match = match.NextMatch();
  }
}

奇抜な出力でかなりのテストを行いました。出力は、サルが入力して<=>を実行したもののかなりの割合と一致します。

現在、これは私が持っているコードです:

    private String[] SplitCommandLineArgument(String argumentString)
    {
        StringBuilder translatedArguments = new StringBuilder(argumentString);
        bool escaped = false;
        for (int i = 0; i < translatedArguments.Length; i++)
        {
            if (translatedArguments[i] == '"')
            {
                escaped = !escaped;
            }
            if (translatedArguments[i] == ' ' && !escaped)
            {
                translatedArguments[i] = '\n';
            }
        }

        string[] toReturn = translatedArguments.ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
        for(int i = 0; i < toReturn.Length; i++)
        {
            toReturn[i] = RemoveMatchingQuotes(toReturn[i]);
        }
        return toReturn;
    }

    public static string RemoveMatchingQuotes(string stringToTrim)
    {
        int firstQuoteIndex = stringToTrim.IndexOf('"');
        int lastQuoteIndex = stringToTrim.LastIndexOf('"');
        while (firstQuoteIndex != lastQuoteIndex)
        {
            stringToTrim = stringToTrim.Remove(firstQuoteIndex, 1);
            stringToTrim = stringToTrim.Remove(lastQuoteIndex - 1, 1); //-1 because we've shifted the indicies left by one
            firstQuoteIndex = stringToTrim.IndexOf('"');
            lastQuoteIndex = stringToTrim.LastIndexOf('"');
        }
        return stringToTrim;
    }

引用符をエスケープしても機能しませんが、これまでに出くわしたケースでは機能します。

これは、エスケープされた引用符では機能しないアントンのコードへの返信です。 3つの場所を変更しました。

  1. SplitCommandLineArguments StringBuilder コンストラクタ \ <!> quot; に置き換えます。 \ r
  2. SplitCommandLineArguments forループで、 \ r 文字を \ <!> quotに戻します。
  3. SplitCommandLineArgument メソッドを private から public static に変更しました。

public static string[] SplitCommandLineArgument( String argumentString )
{
    StringBuilder translatedArguments = new StringBuilder( argumentString ).Replace( "\\\"", "\r" );
    bool InsideQuote = false;
    for ( int i = 0; i < translatedArguments.Length; i++ )
    {
        if ( translatedArguments[i] == '"' )
        {
            InsideQuote = !InsideQuote;
        }
        if ( translatedArguments[i] == ' ' && !InsideQuote )
        {
            translatedArguments[i] = '\n';
        }
    }

    string[] toReturn = translatedArguments.ToString().Split( new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries );
    for ( int i = 0; i < toReturn.Length; i++ )
    {
        toReturn[i] = RemoveMatchingQuotes( toReturn[i] );
        toReturn[i] = toReturn[i].Replace( "\r", "\"" );
    }
    return toReturn;
}

public static string RemoveMatchingQuotes( string stringToTrim )
{
    int firstQuoteIndex = stringToTrim.IndexOf( '"' );
    int lastQuoteIndex = stringToTrim.LastIndexOf( '"' );
    while ( firstQuoteIndex != lastQuoteIndex )
    {
        stringToTrim = stringToTrim.Remove( firstQuoteIndex, 1 );
        stringToTrim = stringToTrim.Remove( lastQuoteIndex - 1, 1 ); //-1 because we've shifted the indicies left by one
        firstQuoteIndex = stringToTrim.IndexOf( '"' );
        lastQuoteIndex = stringToTrim.LastIndexOf( '"' );
    }
    return stringToTrim;
}

C#アプリケーションには単一引用符や^引用符はないと思います。 次の機能は正常に機能しています:

public static IEnumerable<String> SplitArguments(string commandLine)
{
    Char quoteChar = '"';
    Char escapeChar = '\\';
    Boolean insideQuote = false;
    Boolean insideEscape = false;

    StringBuilder currentArg = new StringBuilder();

    // needed to keep "" as argument but drop whitespaces between arguments
    Int32 currentArgCharCount = 0;                  

    for (Int32 i = 0; i < commandLine.Length; i++)
    {
        Char c = commandLine[i];
        if (c == quoteChar)
        {
            currentArgCharCount++;

            if (insideEscape)
            {
                currentArg.Append(c);       // found \" -> add " to arg
                insideEscape = false;
            }
            else if (insideQuote)
            {
                insideQuote = false;        // quote ended
            }
            else
            {
                insideQuote = true;         // quote started
            }
        }
        else if (c == escapeChar)
        {
            currentArgCharCount++;

            if (insideEscape)   // found \\ -> add \\ (only \" will be ")
                currentArg.Append(escapeChar + escapeChar);       

            insideEscape = !insideEscape;
        }
        else if (Char.IsWhiteSpace(c))
        {
            if (insideQuote)
            {
                currentArgCharCount++;
                currentArg.Append(c);       // append whitespace inside quote
            }
            else
            {
                if (currentArgCharCount > 0)
                    yield return currentArg.ToString();

                currentArgCharCount = 0;
                currentArg.Clear();
            }
        }
        else
        {
            currentArgCharCount++;
            if (insideEscape)
            {
                // found non-escaping backslash -> add \ (only \" will be ")
                currentArg.Append(escapeChar);                       
                currentArgCharCount = 0;
                insideEscape = false;
            }
            currentArg.Append(c);
        }
    }

    if (currentArgCharCount > 0)
        yield return currentArg.ToString();
}

昨日投稿したコードを見ることができます:

[C#]パス<!> amp;引数文字列

ファイル名+引数をstring []に分割します。短いパス、環境変数、および欠落しているファイル拡張子が処理されます。

(最初はレジストリ内のUninstallString用でした。)

このコードを試してください:

    string[] str_para_linha_comando(string str, out int argumentos)
    {
        string[] linhaComando = new string[32];
        bool entre_aspas = false;
        int posicao_ponteiro = 0;
        int argc = 0;
        int inicio = 0;
        int fim = 0;
        string sub;

        for(int i = 0; i < str.Length;)
        {
            if (entre_aspas)
            {
                // Está entre aspas
                sub = str.Substring(inicio+1, fim - (inicio+1));
                linhaComando[argc - 1] = sub;

                posicao_ponteiro += ((fim - posicao_ponteiro)+1);
                entre_aspas = false;
                i = posicao_ponteiro;
            }
            else
            {
            tratar_aspas:
                if (str.ElementAt(i) == '\"')
                {
                    inicio = i;
                    fim = str.IndexOf('\"', inicio + 1);
                    entre_aspas = true;
                    argc++;
                }
                else
                {
                    // Se não for aspas, então ler até achar o primeiro espaço em branco
                    if (str.ElementAt(i) == ' ')
                    {
                        if (str.ElementAt(i + 1) == '\"')
                        {
                            i++;
                            goto tratar_aspas;
                        }

                        // Pular os espaços em branco adiconais
                        while(str.ElementAt(i) == ' ') i++;

                        argc++;
                        inicio = i;
                        fim = str.IndexOf(' ', inicio);
                        if (fim == -1) fim = str.Length;
                        sub = str.Substring(inicio, fim - inicio);
                        linhaComando[argc - 1] = sub;
                        posicao_ponteiro += (fim - posicao_ponteiro);

                        i = posicao_ponteiro;
                        if (posicao_ponteiro == str.Length) break;
                    }
                    else
                    {
                        argc++;
                        inicio = i;
                        fim = str.IndexOf(' ', inicio);
                        if (fim == -1) fim = str.Length;

                        sub = str.Substring(inicio, fim - inicio);
                        linhaComando[argc - 1] = sub;
                        posicao_ponteiro += fim - posicao_ponteiro;
                        i = posicao_ponteiro;
                        if (posicao_ponteiro == str.Length) break;
                    }
                }
            }
        }

        argumentos = argc;

        return linhaComando;
    }

ポルトガル語で書かれています。

ジョブを完了する1つのライナーがあります(BurstCmdLineArgs(...)メソッド内ですべての作業を行う1行を参照してください)。

私が最も読みやすいコード行とは言いませんが、読みやすくするためにコードを分割できます。意図的に単純であり、すべての引数の場合(分割文字列の区切り文字を含むファイル名引数など)にはうまく機能しません。

このソリューションは、それを使用する私のソリューションでうまく機能しました。私が言ったように、それは、すべての可能な引数形式n階乗を処理するために、ラットの巣のコードなしで仕事をします。

using System;
using System.Collections.Generic;
using System.Linq;

namespace CmdArgProcessor
{
    class Program
    {
        static void Main(string[] args)
        {
            // test switches and switches with values
            // -test1 1 -test2 2 -test3 -test4 -test5 5

            string dummyString = string.Empty;

            var argDict = BurstCmdLineArgs(args);

            Console.WriteLine("Value for switch = -test1: {0}", argDict["test1"]);
            Console.WriteLine("Value for switch = -test2: {0}", argDict["test2"]);
            Console.WriteLine("Switch -test3 is present? {0}", argDict.TryGetValue("test3", out dummyString));
            Console.WriteLine("Switch -test4 is present? {0}", argDict.TryGetValue("test4", out dummyString));
            Console.WriteLine("Value for switch = -test5: {0}", argDict["test5"]);

            // Console output:
            //
            // Value for switch = -test1: 1
            // Value for switch = -test2: 2
            // Switch -test3 is present? True
            // Switch -test4 is present? True
            // Value for switch = -test5: 5
        }

        public static Dictionary<string, string> BurstCmdLineArgs(string[] args)
        {
            var argDict = new Dictionary<string, string>();

            // Flatten the args in to a single string separated by a space.
            // Then split the args on the dash delimiter of a cmd line "switch".
            // E.g. -mySwitch myValue
            //  or -JustMySwitch (no value)
            //  where: all values must follow a switch.
            // Then loop through each string returned by the split operation.
            // If the string can be split again by a space character,
            // then the second string is a value to be paired with a switch,
            // otherwise, only the switch is added as a key with an empty string as the value.
            // Use dictionary indexer to retrieve values for cmd line switches.
            // Use Dictionary::ContainsKey(...) where only a switch is recorded as the key.
            string.Join(" ", args).Split('-').ToList().ForEach(s => argDict.Add(s.Split()[0], (s.Split().Count() > 1 ? s.Split()[1] : "")));

            return argDict;
        }
    }
}

ここで気に入ったものは見つかりませんでした。小さなコマンドラインのyieldマジックでスタックを台無しにするのは嫌いです(テラバイトのストリームであれば、別の話になります)。

これが私の見解です。次のような二重引用符による引用エスケープをサポートしています。

  

param = <!> quot; a 15 <!> quot; <!> quot;画面は悪くない<!> quot; param2 = 'a 15 <!> quot; screen isn''t bad 'param3 = <!> quot; <!> quot; param4 = / param5

結果:

  

param = <!> quot; a 15 <!> quot;画面は悪くない<!> quot;

     

param2 = 'a 15 <!> quot;画面は悪くない」

     

param3 = <!> quot; <!> quot;

     

param4 =

     

/ param5

public static string[] SplitArguments(string commandLine)
{
    List<string> args         = new List<string>();
    List<char>   currentArg   = new List<char>();
    char?        quoteSection = null; // Keeps track of a quoted section (and the type of quote that was used to open it)
    char[]       quoteChars   = new[] {'\'', '\"'};
    char         previous     = ' '; // Used for escaping double quotes

    for (var index = 0; index < commandLine.Length; index++)
    {
        char c = commandLine[index];
        if (quoteChars.Contains(c))
        {
            if (previous == c) // Escape sequence detected
            {
                previous = ' '; // Prevent re-escaping
                if (!quoteSection.HasValue)
                {
                    quoteSection = c; // oops, we ended the quoted section prematurely
                    continue;         // don't add the 2nd quote (un-escape)
                }

                if (quoteSection.Value == c)
                    quoteSection = null; // appears to be an empty string (not an escape sequence)
            }
            else if (quoteSection.HasValue)
            {
                if (quoteSection == c)
                    quoteSection = null; // End quoted section
            }
            else
                quoteSection = c; // Start quoted section
        }
        else if (char.IsWhiteSpace(c))
        {
            if (!quoteSection.HasValue)
            {
                args.Add(new string(currentArg.ToArray()));
                currentArg.Clear();
                previous = c;
                continue;
            }
        }

        currentArg.Add(c);
        previous = c;
    }

    if (currentArg.Count > 0)
        args.Add(new string(currentArg.ToArray()));

    return args.ToArray();
}

あなたを理解しているかどうかはわかりませんが、スプリッターとして使用される文字もテキスト内にあるという問題はありますか? (それ以外は、二重の<!> quot ;?でエスケープされます)

もしそうなら、forループを作成し、<!> lt; <!> quot; <!> gt;のすべてのインスタンスを置き換えます。 <!> lt; | <!> gt; (または別の<!> quot; safe <!> quot;文字、ただし<!> lt; <!> quot; <!> gt;のみを置き換え、<!> lt; <!> quotは置き換えないことを確認してください; <!> quot; <!> gt;

文字列を繰り返した後、以前に投稿したように、文字列を分割しますが、文字<!> lt; | <!> gt;で行います。

はい、文字列オブジェクトにはSplit()という組み込み関数があり、区切り文字として検索する文字を指定する単一のパラメーターを受け取り、個々の値を含む文字列の配列(string [])を返します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top