简体   繁体   English

RegEx替换和替换字符串

[英]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. 我遇到的问题是FindDefinition方法。 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. 哪种方法可以与FindDefinition方法配合使用,但是在获取原始值时遇到了问题。

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. 您正在手工构建XML,这几乎总是错误的。

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. 我倾向于使用类似m.Groups [0] .Value之类的东西,并在正则表达式中使用分组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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