Jump to content

How to quickly find the last match in a string in C#

0
  LaurelRuma's Photo
Posted Oct 01 2009 12:10 PM

You need to find the last pattern match in a string, but you do not want the overhead of finding all matches in a string and having to move to the last match in the collection of matches.

To execute a regular expression starting from the end of the string, use the RegexOptions.RightToLeft flag. The first found match is the last match in the string. You supply the RegexOptions.RightToLeft constant as an argument to the Match method. The instance Match method can be used as follows:

Regex RE = new Regex(Pattern, RegexOptions.RightToLeft);
	Match theMatch = RE.Match(Sourcet);


or use the static Regex.Match method:

	Match theMatch = Regex.Match(Source, Pattern, RegexOptions.RightToLeft);



where Pattern is the regular expression pattern and Source is the string against which to run the pattern.

The RegexOptions.RightToLeft regular expression option will force the regular expression engine to start searching for a pattern starting with the end of the string and proceeding backward toward the beginning of the string. The first match encountered will be the match closest to the end of the string—in other words, the last match in the string.
Cover of C# 3.0 Cookbook
Learn more about this topic from C# 3.0 Cookbook, 3rd Edition. 

Completely updated for C# 3.0 and the .NET 3.5 platform, the new edition of this bestseller offers more than 250 code recipes to common and not-so-common problems that C# programmers face every day. More than a third of the recipes have been rewritten to take advantage of new C# 3.0 features. If you prefer solutions to general C# language instruction and quick answers to theory, this is your book.

Learn More Read Now on Safari


Tags:
0 Subscribe


0 Replies