简体   繁体   中英

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?

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.

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