using System; using System.Text.RegularExpressions; using System.IO; using System.Linq; public class Test { public static readonly Regex rxQuoted = new Regex(@"""([^""\\]*(?:\\.[^\\""]*)*)"""); public static void Main() { // 1. Regex: \b(?:to\ background)\b, Match: N/A checkIt("to background", "I need to find a string in this sentence!"); // 2. Regex: \b(?:to|background)\b, Match: to checkIt("\"to\" \"background\"", "I need to find a string in this sentence!"); // 3. Regex: \b(?:to\ find)\b, Match: to find checkIt("\"to find\"", "I need to find a string in this sentence!"); } public static void checkIt(string searchString, string sentence) { var lst = rxQuoted.Matches(searchString) .Cast() .Select(p => Regex.Escape(p.Groups[1].Value)) .ToList(); var pattern = lst.Count > 0 ? @"\b(?:" + String.Join("|", lst) + @")\b" : @"\b(?:" + Regex.Escape(searchString) + @")\b"; Console.WriteLine("Regex: " + pattern); Match match = Regex.Match(sentence, pattern); if (match.Success) { Console.WriteLine("Match value: " + match.Value); } } }