How do I match the last character in an arbitrary string using C# Regexes?

.net, regex

Solution

.NET supports the `\z` token, which always matches the end of the string:

Regex.Replace(input, @".\z", "X", RegexOptions.Singleline);

Problem

The obvious attempt is: ``` Regex.Replace(input, @".$", "X", RegexOptions.Singleline); ``` This doesn't always work though. Consider the string `\r\n\r\n` - the above produces the surprising result of `\r\nXX`. One might expect from reading MSDN (under Multiline) that `$` should match just at the end of the entire string, but apparently `$` actually means "match at end of string or at the `\n` just before the end of string". What might be a correct way to match the last character of an arbitrary string?

Original source