• .NET 正则表达式’$’符号的使用


    .NET中的System.Text.RegularExpressions.Regex类是非常好用的一个类。

    最近在使用Regex.Replace(…)方法时,对于替换字符串中使用的“$0”,“$1”等东西比较迷糊。在网上简单搜索了一下,没有找到什么好的回答。

    于是,自己摸索了一下,原来如此啊微笑

    我们先看如下代码:

                string pattern = "Tom";
                var input = "Tom is not tom.";
                // I wanna to replace 'Tom' to 'Tomas'
                var output = Regex.Replace(input, pattern, "$0as");
                Console.WriteLine(output);
    

    在替换字符串参数中,使用了“$0”,意思就是将匹配到的字符串作为替换字符串的一部分,上例中,匹配到”Tom”,然后就会被替换为“Tomas”。

    另外,替换对于“$1”,又是什么意思呢?看下面的例子:

                string pattern = "CLR (via) C#";
                var input = "I like 'CLR via C#'";
                // I wanna to replace 'CLR via C#' to 'Windows via C++'
                var output = Regex.Replace(input, pattern, "Windows $1 C++");
                Console.WriteLine(output);

    上例中使用了“$1”,在进行替换操作的时候“$1”代表的就是正则表达式中第一个加小括号的部分,即“via”。

    在实际的工作中,使用“$0”,“$1”,有时会起到不错的效果。

  • 相关阅读:
    统计脚本代码行数
    expr算术运算
    lsof命令
    测试当前机器可以创建多少线程
    守护进程写日志
    文件描述符fd,struct files_struct
    linux查看反汇编
    信号补充
    Windows10获取VS管理员权限总是很烦人
    asp.net中的Filter类型其实是被当作单例的
  • 原文地址:https://www.cnblogs.com/quark/p/2108076.html
Copyright © 2020-2023  润新知