C#Regex - 用自己替换 [英] C# Regex - Replace with itself
问题描述
在想格式化编程HTML标签的文章。什么是找到文章中的模式并用本身附加在每边的标签替换它的最佳方式?更具体地讲,我怎么可以通过下面的例子将比赛拖入 thematch
:
字符串formattedArticle
= Regex.Replace(文章^ \d +,<环境监察及GT;+ thematch +< / EM>);
的的说明文档:
<块引用>
的
$&安培;
替换包括替换字符串整场比赛
块引用> $ b $。 b
事实上,在他们的榜样,他们提出一个使用案例非常相似,你的:
通常情况下,它是。用来添加一个字符串来匹配字符串的开头或结尾
块引用>
所以你的情况,你可以这样写:
(^ \d +的文章,< EM> $&安培;< / EM>)
Regex.Replace ;
In want to format an article with HTML tags programmatically. What is the best way to find a pattern in the article and replace it with itself with the tags appended on each side? More specifically, how can I pass the match into
thematch
in the following example:string formattedArticle = Regex.Replace(article, "^\d.+", "<em>" + thematch + "</em>");
解决方案The documentation explains:
The
$&
substitution includes the entire match in the replacement string.In fact, in their example they present a use case very similar to yours:
Often, it is used to add a substring to the beginning or end of the matched string.
So in your case you can write:
Regex.Replace(article, "^\d.+", "<em>$&</em>");
这篇关于C#Regex - 用自己替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!