user8652852
user8652852

Reputation:

Look for substring in string to find part before searched sentence

In:

 string str = "On the screen the faint, old, robed figure of Mercer toiled upward, and all at once a rock sailed past him.";

search for sub-string:

 string find = "figure of";

if this way:

 string reg = string.Format("({0} +([\\w+]+))", find);
 var result = new Regex(reg).Match(str);

I can get part followed to searched sentence:

figure of Mercer

But how to find part of phrase before searched sentence:

 On the screen the faint, old, robed

And get only nearest word:

 robed

Upvotes: 0

Views: 39

Answers (1)

Backs
Backs

Reputation: 24913

IndexOf will help to find starting index of Substing

string str = "On the screen the faint, old, robed figure of Mercer toiled upward, and all at once a rock sailed past him.";
string find = "figure of";

var index = str.IndexOf(find);

if (index >= 0)
{
    var result = str.Substring(0, index);
    Console.WriteLine(result);
}

Upvotes: 1

Related Questions