June
June

Reputation: 1014

Regular expression replace text contents

I have this paragraph:

"This person name #Question1#, #Question2#, has #Question3# been drinking in the past two days."

I use regex to find an array of matching entries for #Question[0-9]+#, my question is, how can utilise the regex feature to replace these #Question[0-9]+# with actual answers from my database.

Here is my code

        const string pattern = @"#Question([0-9]+)#";
        string input = template.GetPrintOut;
        MatchCollection matches = Regex.Matches(input, pattern);

I can provide a dictionary of replacing string from database. Any ideas?

Upvotes: 0

Views: 106

Answers (1)

Felice Pollano
Felice Pollano

Reputation: 33252

Of course, use Regex.Replace:

var res = reg.Replace(text, match => { ....; return "reply"; });

In the match lambda you can recover the data based on the match value and return the reply accordingly.

Upvotes: 3

Related Questions