正则表达式查找并替换以包装标签 [英] Regular expression find and replace to wrap tags

查看:95
本文介绍了正则表达式查找并替换以包装标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何使用正则表达式来查找和替换某些单词

Does anyone know how to use regex to find and replace certain word with

<b>[Keyword]</b>

我尝试使用 Regex.Replace() ,但它似乎仅支持直接替换而不是附加< b>< / b> 在关键字的开头和结尾。

I tried to use Regex.Replace() but it seems it only support direct replacement instead of appending <b></b> at begin and last of the keyword.

示例:

Hello World!

关键字:

Hello

输出:

<b>Hello</b> World!


推荐答案

您可以尝试以下方法:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string
            input = "Hello World!",
            keyword = "Hello";

        var result = Regex
            .Replace(input, keyword, m => 
                String.Format("<b>{0}</b>", m.Value));
        Console.WriteLine(result);
    }
}

这篇关于正则表达式查找并替换以包装标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆