Roman Starkov
Roman Starkov

Reputation: 61382

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

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?

Upvotes: 2

Views: 2364

Answers (1)

Timwi
Timwi

Reputation: 66573

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

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

Upvotes: 8

Related Questions