nupanick

PythonRegex.cs

Jun 24th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.42 KB | None | 0 0
  1. public IList<string> PythonRegex(
  2.     string needle,
  3.     string haystack,
  4.     bool enhanceMatch = false,
  5.     bool bestMatch = false)
  6. {
  7.     var argNeedle = needle.Replace("'", @"\'");
  8.     var argHaystack = haystack.Replace("'", @"\'");
  9.     var pyCommand = (
  10.         $"import regex;" +
  11.         $"import json;" +
  12.         $"t=regex.search('{argNeedle}','{argHaystack}'," +
  13.         (enhanceMatch ? "regex.ENHANCEMATCH," : "") +
  14.         (bestMatch ? "regex.BESTMATCH," : "") +
  15.         $");" +
  16.         $"print(t.group(0));" +
  17.         $"print(json.dumps(t.groups()));"
  18.         );
  19.     ProcessStartInfo pyStart = new ProcessStartInfo
  20.     {
  21.         FileName = @"python",
  22.         Arguments = $"-c \"{pyCommand}\"",
  23.         UseShellExecute = false,
  24.         RedirectStandardOutput = true,
  25.         RedirectStandardError = true,
  26.     };
  27.  
  28.     string[] groups = null;
  29.     using (var pyProcess = Process.Start(pyStart))
  30.     using (var reader = pyProcess.StandardOutput)
  31.     using (var error = pyProcess.StandardError)
  32.     {
  33.         var err = error.ReadToEnd();
  34.         if (!String.IsNullOrWhiteSpace(err))
  35.         {
  36.             throw new ArgumentException(err);
  37.         }
  38.         var first = reader.ReadLine();
  39.         var others = reader.ReadLine();
  40.         groups = new object[] { first }
  41.             .Concat(JArray.Parse(others))
  42.             .Select(t => t.ToString())
  43.             .ToArray();
  44.     }
  45.     return groups;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment