Regex - replace only the last part of an expression

I am trying to find the best methodology to find a specific pattern and then replace the trailing part of the picture. Here's a quick example (in C #):

// Find any year value that starts with a parenthesis 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've tried using Regex.Replace () but can't figure out if it can be applied.

If all else fails, I can find matches using MatchCollection and then turn off the value 2007 from 2008; however, I hope for something more elegant

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

      

+1


source to share


3 answers


Your pattern does not work as described: as described, you have to start with " \[|_

" (pipe means OR), and the solution to your real problem is regex grouping. Highlight the part of the pattern you are interested in within the "(" and ")" brackets and you can access them in replacement.

So you need a template like this: /^(\[|_)2007/

edit: .NET code



string s = Regex.Replace(source, @"^(\[|_)2007", @"$12008");

      

nb misunderstood requirement, sample changed

+5


source


You can wrap the part you want to keep in parentheses to create a group of subheadings. Then, in the replacement text, use the backlink to get it back. If I understand what you are trying to do the right thing, you would do something like this:

Regex yearFind = new Regex("([[_])2007");
yearFine.Replace("_2007", @"$12008"); // => "_2008"
yearFine.Replace("[2007", @"$12008"); // => "[2008"

      



"$ 1" in the replacement text is replaced with whatever was matched within the parentheses.

+2


source


Show substitution (using vim in this case). if I have a file with the following content:

aaa _2007
bbb , 2007
ccc [2007]

      

and i am using regex

:1,$ s/\([_[ ]\)\(2007\)/\12008/g

      

The first group (in (,)) will match the character preceding the year, and the second group will match the year 2007. The substitution replaces the first match and overwrites whatever matched the second group from 2008, serve:

aaa _2008
bbb , 2008
ccc [2008]

      

Various regex libraries will have minor syntactic variations along this principle.

+1


source







All Articles