fork(2) download
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.IO;
  4. using System.Linq;
  5. public class Test
  6. {
  7. public static readonly Regex rxQuoted = new Regex(@"""([^""\\]*(?:\\.[^\\""]*)*)""");
  8. public static void Main()
  9. {
  10. // 1. Regex: \b(?:to\ background)\b, Match: N/A
  11. checkIt("to background", "I need to find a string in this sentence!");
  12. // 2. Regex: \b(?:to|background)\b, Match: to
  13. checkIt("\"to\" \"background\"", "I need to find a string in this sentence!");
  14. // 3. Regex: \b(?:to\ find)\b, Match: to find
  15. checkIt("\"to find\"", "I need to find a string in this sentence!");
  16. }
  17. public static void checkIt(string searchString, string sentence)
  18. {
  19. var lst = rxQuoted.Matches(searchString)
  20. .Cast<Match>()
  21. .Select(p => Regex.Escape(p.Groups[1].Value))
  22. .ToList();
  23. var pattern = lst.Count > 0 ?
  24. @"\b(?:" + String.Join("|", lst) + @")\b" :
  25. @"\b(?:" + Regex.Escape(searchString) + @")\b";
  26. Console.WriteLine("Regex: " + pattern);
  27.  
  28. Match match = Regex.Match(sentence, pattern);
  29. if (match.Success)
  30. {
  31. Console.WriteLine("Match value: " + match.Value);
  32. }
  33. }
  34. }
Success #stdin #stdout 0.13s 24696KB
stdin
Standard input is empty
stdout
Regex: \b(?:to\ background)\b
Regex: \b(?:to|background)\b
Match value: to
Regex: \b(?:to\ find)\b
Match value: to find