1
votes

I need to acomplish the following and unsure of the best methods.

Take the following string as an example.

%%%% START %%%%

sit amet ipsum sagittis luctus eu id diam. [%RC:3%] Morbi suscipit iaculis accumsan. Morbi laoreet consectetur nisl, luctus tempor felis ultrices commodo. Praesent dui augue, interdum non rutrum vel, vestibulum sit amet lorem. Nam sit amet erat elit, et porta mi. Vestibulum non urna magna. Phasellus pharetra rutrum urna quis tincidunt. Duis metus quam, fermentum sed ultricies id, tincidunt id ipsum. [%RC:1%]

%%%% END %%%%

What i need to be able to do is take that string and firstly find all the occurences of the "tokens" [%RC:(int)%], get the id that is contained within that token (which will be used to query data) and then replace that whole token with a new string.

How would i do this? Any advice & guidance would be great.

1

1 Answers

3
votes

Assuming you have a dictionary that you can use to look up the replacement string, try using the overload of Regex.Replace that takes a MatchEvaluator:

string result = Regex.Replace(
    text,
    @"\[%RC:(\d+)%\]",
    match => dict[int.Parse(match.Groups[1].Value)]);

See it working online: ideone