简体   繁体   中英

Replace specific instance of item in string with regex

I am trying to build a parser that will replace a specific instance of a string. So for example I have a string that is sn+sn+sn*9 , and I want to only replace the third instance of sn How can I do this with regex?

I have tried

var expression = "sn+sn+sn*9";
var regex = new Regex("sn");
expression = regex.Replace("sn",4.ToString());
//expression = regex.Replace("sn",4.ToString(),1,2);

Thanks in advance

int x = 0;
string repl = "ANYTHING";
string s = Regex.Replace("sn+sn+sn*9", "sn", m => (++x) == 3 ? repl : m.Value);

Explanation

The x variable is used to track the occurrence of sought text. As soon as Regex finds third occurrence, the MatchEvaluator delegate replaces this string with whatever is in repl variable. Otherwise, it just returns the same found string.

Here is one option, which uses the following regex pattern:

(?<=.*?\bsn\b.*?\bsn\b.*?)\bsn\b

This pattern literally says to replace sn , as a single term, when we have already seen two sn terms previously in the string. I use the replacement blah in the sample code below, though you may use any value you wish.

var term = @"sn";
var replacement = "blah";
var expression = term + "+" + term + "+" + term + "*9";
var pattern = @"(?<=.*?\b" + term + @"\b.*?\b" + term + @"\b.*?)\b" + term + @"\b";
var exp_trim = Regex.Replace(expression, @pattern, replacement);
Console.WriteLine(exp_trim);

sn+sn+blah*9

Demo

Here is another method using the index and length of the match

           string expression = "sn+sn+sn*9";
            Regex regex = new Regex("sn");
            MatchCollection matches = regex.Matches(expression);
            expression = expression.Substring(0, matches[2].Index) + "4".ToString() + expression.Substring(matches[2].Index + matches[2].Length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM