2

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?

3
  • 4
    Why REGEX?!? WHY!!!! Just split on \r\n and iterate the lines, getting the last character. Regex is not the solution for everything. Commented Nov 18, 2009 at 2:51
  • 1
    There's more involved than just matching the last character. Of course if I wanted just the last character then I'd just go input[input.Length - 1]... No splitting of any kind required. Commented Nov 18, 2009 at 2:53
  • 3
    Why not just program in regex and forget C#. Commented Nov 18, 2009 at 3:12

1 Answer 1

8

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

Regex.Replace(input, @".\z", "X", RegexOptions.Singleline);
Sign up to request clarification or add additional context in comments.

1 Comment

I've got a CLR Assembly using .Net regex and this is perfect for what I need it to do. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.