Jim Mischel的評論中的link指出,Win32 API爲此提供了一個函數。我建議使用它來保持一致性。以下是一個示例(來自PInvoke)。
static string[] SplitArgs(string unsplitArgumentLine)
{
int numberOfArgs;
IntPtr ptrToSplitArgs;
string[] splitArgs;
ptrToSplitArgs = CommandLineToArgvW(unsplitArgumentLine, out numberOfArgs);
if (ptrToSplitArgs == IntPtr.Zero)
throw new ArgumentException("Unable to split argument.",
new Win32Exception());
try
{
splitArgs = new string[numberOfArgs];
for (int i = 0; i < numberOfArgs; i++)
splitArgs[i] = Marshal.PtrToStringUni(
Marshal.ReadIntPtr(ptrToSplitArgs, i * IntPtr.Size));
return splitArgs;
}
finally
{
LocalFree(ptrToSplitArgs);
}
}
[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW(
[MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
out int pNumArgs);
[DllImport("kernel32.dll")]
static extern IntPtr LocalFree(IntPtr hMem);
如果你想快速和骯髒的,不靈活的,脆弱的正則表達式的解決方案,你可以做這樣的事情:
var rex = new Regex(@"("".*?""|[^ ""]+)+");
string test = "CALL \"C:\\My File Name With Space\" /P1 P1Value /P1 P2Value";
var array = rex.Matches(test).OfType<Match>().Select(m => m.Groups[0]).ToArray();
是不是你在Main()中將字符串數組作爲命令行參數? –
不,我正在解析文件夾中的批處理文件。 – ChadD
我不會使用正則表達式來處理這個問題。命令行中有太多特殊情況。你最好使用http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c?rq=1的建議之一,或者只是寫你的自己的(這可能需要幾個小時)。 –