简体   繁体   中英

RegEx Replace and replacement string

I've got the following code:

Regex.Replace(text, words.ToString(), "<dfn title=\"" + this.FindDefinition("$0")  + "\">$0</dfn>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

The problem I'm having is with the FindDefinition method. I would like to send in the originale word to make a lookup and return the definition text. Is this possible or do I need to create a template like this:

Regex.Replace(text, words.ToString(), "<dfn title=\"{$0}\">$0</dfn>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

And then do a search for it to replace it with my definition?

I've also tried with:

Regex.Replace(text, words.ToString(), this.ReplaceWord, RegexOptions.IgnoreCase | RegexOptions.Compiled); 

private string ReplaceWord(Match m)
{
    return "<dfn title=\"" + this.FindDefinition(m.Value) + "\">$0</dfn>";
}

Which works fine with the FindDefinition method, but then I have a problem getting the original value.

Anything I'm missing?

Try this:

return string.Format("<dfn title=\"{0}\">{1}</dfn>",
                     this.FindDefinition(m.Value),
                     m.Value);

You're building XML by hand, it's almost always plain wrong.

You'll need to use the evaluator (replaceword). Why don't you do something like:

private string ReplaceWord(Match m)
{
    return "<dfn title=\"" + this.FindDefinition(m.Value) + "\">"+m.Value+"</dfn>";
}

I'd tend to use something like m.Groups[0].Value and use grouping in regex.

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