简体   繁体   English

C#Regex.Replace不区分大小写,作为匹配的函数

[英]C# Regex.Replace case insensitive as a function of the match

Say I have some text like this: 说我有这样的文字:

string text = "Hello world! hElLo world!";

I want to add a span tag around each of the words 'hello' in a case insensitive way so that the result is this: 我想以不区分大小写的方式在每个单词'hello'周围添加一个span标记,以便结果如下:

string text = "<span>Hello</span> world! <span>hElLo</span> world!";

I tried to do this with Regex.Replace like so: 我尝试用Regex.Replace这样做:

Regex.Replace(text, "hello", "<span>hello</span>", RegexOptions.IgnoreCase);

But what I really need is just the span tags to be created, leaving the original casing alone. 但我真正需要的只是要创建的span标签,只保留原始外壳。 So I would need the replace phrase to be a function of the matched phrase. 所以我需要替换短语是匹配短语的函数。 How can I do this? 我怎样才能做到这一点?

Instead of hard-coding the hello in the replacement pattern, use a $& backreference to the entire match value. 不要在替换模式中对hello进行硬编码,而是对整个匹配值使用$& backreference。

Replace "<span>hello</span>" with "<span>$&</span>" , use "<span>hello</span>"替换为"<span>$&</span>" ,使用

var replaced = Regex.Replace(text, "hello", "<span>$&</span>", RegexOptions.IgnoreCase);

See more about replacement backreferences in Substitutions in Regular Expressions . 查看有关正则表达式替换中的替换反向引用的更多信息。

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

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