fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5.  
  6. public static class Test
  7. {
  8. private static Regex qoutesRegex = new Regex("(?<!\\\\)\\\"", RegexOptions.Compiled);
  9.  
  10. public static IEnumerable<string> Split(this string str,
  11. Func<char, bool> controller)
  12. {
  13. int nextPiece = 0;
  14.  
  15. for (int c = 0; c < str.Length; c++)
  16. {
  17. if (controller(str[c]))
  18. {
  19. yield return str.Substring(nextPiece, c - nextPiece);
  20. nextPiece = c + 1;
  21. }
  22. }
  23.  
  24. yield return str.Substring(nextPiece);
  25. }
  26.  
  27.  
  28. public static IEnumerable<string> SplitCommandLine(string commandLine)
  29. {
  30. bool inQuotes = false;
  31. bool isEscaping = false;
  32.  
  33. return commandLine.Split(c => {
  34. if (c == '\\' && !isEscaping) { isEscaping = true; return false; }
  35.  
  36. if (c == '\"' && !isEscaping)
  37. inQuotes = !inQuotes;
  38.  
  39. isEscaping = false;
  40.  
  41. return !inQuotes && Char.IsWhiteSpace(c)/*c == ' '*/;
  42. })
  43. .Select(arg => arg.Trim())
  44. .Select(arg => qoutesRegex.Replace(arg, "").Replace("\\\"", "\""))
  45. .Where(arg => !string.IsNullOrEmpty(arg));
  46. }
  47.  
  48. public static void Main()
  49. {
  50. IEnumerable<string> tests = new List<string> (){
  51. "\"He whispered to her \\\"I love you\\\".\"",
  52. "\"C:\\Program Files\"",
  53. "\"He whispered to her \\\"I love you\\\".\"",
  54. "a\" \\\"asdsd \\\"dsdsd AAA\"b",
  55. "\" \\\"asdsd \\\"dsdsd \"basds",
  56. "sdsd\" \\\"asdsd \\\"dsdsd \"",
  57. "\"A\\\"asdsd \\\"dsdsdA\""
  58. };
  59. foreach (var test in tests){
  60. foreach(var s in SplitCommandLine(test)){
  61. Console.WriteLine("Param `{0}`",s);
  62. }
  63. Console.WriteLine("-----------------");
  64. }
  65. }
  66. }
Success #stdin #stdout 0.13s 24712KB
stdin
Standard input is empty
stdout
Param `He whispered to her "I love you".`
-----------------
Param `C:\Program Files`
-----------------
Param `He whispered to her "I love you".`
-----------------
Param `a "asdsd "dsdsd AAAb`
-----------------
Param ` "asdsd "dsdsd basds`
-----------------
Param `sdsd "asdsd "dsdsd `
-----------------
Param `A"asdsd "dsdsdA`
-----------------