c# – Regex for matching substring in a string

Let me provide Regex based solution as a reference in case you have a real regular expression pattern, not just a substring (substringToFind):

using System.Linq;
using System.Text.RegularExpressions;

...

string text = "Tour Text Here";
string substringToFind = "your policy may provide coverage with the Rideshare Coverage";

// If substringToFind contains chars that have special meaning, they have to be escaped
string pattern = Regex.Escape(substringToFind);

// Either position of the first match or -1
int index = Regex
  .Matches(text, pattern)
  .Select(match => match.Index)
  .FirstOrDefault(-1);

When you want substring’s index regex is overshoot; you may want to use regex in more complex cases, e.g. if you want to be sure that policy ... provide coverage ... is within the text:

int index = Regex
  .Matches(text, @"\bpolicy\b.*?\bcoverage\b", RegexOptions.IgnoreCase)
  .Select(match => match.Index)
  .FirstOrDefault(-1);

Read more here: Source link