Warm tip: This article is reproduced from stackoverflow.com, please click
c# split string substring

Extracting a block of text after the last instance of a specific string

发布于 2020-03-27 15:44:03

I have a text file from which I need to extract a block of text after the last instance of a specific string. To better ilustrate what is needed:

SpecificString#1:
 TextBlock#1
SpecificString#2:
 TextBlock#2
...
SpecificString#5:
 TextBlock#5

All specific strings are identical, and the number of instances can vary. So far I am able to extract all TextBlocks after the first instance of the specific string with the following code:

const string separator = "SpecificString";
var separatorIndex = myTextFileString.IndexOf(separator, StringComparison.CurrentCultureIgnoreCase);
var requiredTextBlock = myTextFileString.Substring(separatorIndex + separator.Length);

However I would like to grab only the last block of text (TextBlock#5 in this case). How can I achieve this?

Questioner
Giedrius666
Viewed
84
Abhijit Pal 2020-01-31 16:57

You can get the last index of the separator in C# by using String.LastIndexOf() method. Please take a look at https://docs.microsoft.com/en-us/dotnet/api/system.string.lastindexof?view=netframework-4.8.

Once you know the last index, you can follow the same step as you have mentioned above to extract the text block after it.