Christopher Bruce
Christopher Bruce

Reputation: 701

Replace every occurrence of a Regex match EXCEPT for the first?

I don't have my code with me at home but I realized that I'll need to do a regex replace on a certain expression and I was wondering if there is a best practices for this.

What my code is currently doing is searching for matches in files, taking those matches out of a file(replacing them with ""), and then once all the files are processed I make a call to the .NET Process class to do some command line stuff. Specifically what i'll be doing is taking a group of files and copying them(merging)into one final output file. But there is the instance where every file to be merged has the exact same first line, which let's just say for the example is:

FIRST_NAME|MIDDLE_NAME|LAST_NAME|ADDRESS

Now, the first file having that is okay. And I figure that I'm going to do this final match and replace once the file is merged. But I only want to replace matches of that specific expression AFTER the first occurrence.

So, I read that C# has superb support for a Regex look behind? Would that be the proper way to implement "replacing matches after the first occurrence of a match" and if so how would you implement it given a sample regular expression?

My own personal solution to this was to return the amount of files in the folder with Directory.GetFiles and then in my foreach (string file in matches) I would declare a quick condition that says

if (count == directoryCount)
 do not match and replace
 count minus 1
elseif (count < directoryCount) 
 strip matching expression

and then every iteration through the foreach after the first run-through will strip out the matching expression from the file leaving only the first file with the expression I want to keep.

Thank you for any suggestions.

Upvotes: 1

Views: 619

Answers (2)

user2636807
user2636807

Reputation: 21

how about using replaceFirst() to backup the first occurency and mark it with some char. then use replaceAll(), and replaceFirst() again to roll back the first match.

Upvotes: 1

Mark Hurd
Mark Hurd

Reputation: 10931

Regex.Replace has a couple of overloads that provide for MatchEvaluator evaluator which is delegate on a Match returning the replacement String.

So you can use something like re.Replace(input, m => first ? (first=false, m.Value) : "") (but I've a VB programmer and have put this in without any syntax checking).

Upvotes: 0

Related Questions