Regex - replace only last part of an expression

Posted on Stack Overflow See other posts from Stack Overflow
Published on 2008-12-03T16:13:43Z Indexed on 2011/01/07 17:53 UTC
Read the original article Hit count: 349

Filed under:
|

I'm attempting to find the best methodology for finding a specific pattern and then replace the ending portion of the pattern. Here is a quick example (in C#):

//Find any year value starting with a bracket or underscore

string patternToFind = "[[_]2007";

Regex yearFind = new Regex(patternToFind);

//I want to change any of these values to x2008 where x is the bracket or underscore originally in the text. I was trying to use Regex.Replace(), but cannot figure out if it can be applied.

If all else fails, I can find Matches using the MatchCollection and then switch out the 2007 value with 2008; however, I'm hoping for something more elegant

MatchCollections matches = yearFind.Matches(" 2007 [2007 _2007");
foreach (Match match in matches){
  //use match to find and replace value
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex