简体   繁体   English

如何在Regex.Replace中将匹配项替换为替换字符串?

[英]How do I get the match in a Regex.Replace into the replacement string?

I need the match in the Regex.Replace to be part of the replacement string. 我需要Regex.Replace中的匹配项作为替换字符串的一部分。 For example, if I want to change DOMAIN to <a>DOMAIN</a> , wherever it says DOMAIN. 例如,如果我想将DOMAIN更改为<a>DOMAIN</a> ,无论它在何处显示DOMAIN。 How do I get DOMAIN into the match? 如何让DOMAIN进入比赛?

regex.Replace(input, String.Format("<a>{0}</a>" WHAT_HERE?));

How do I find the "WHAT_HERE?"? 如何找到“ WHAT_HERE”?

You can use a grouping construct (...) : 您可以使用分组构造 (...)

string replaced = Regex.Replace("<input>", "(DOMAIN)", "<a>$1</a>");

Example: https://dotnetfiddle.net/Hu0cEO 示例: https //dotnetfiddle.net/Hu0cEO

Andrew's answer is correct, here's how you'd do it if you wanted to name the grouping and then replace it by name (expanded from Andrew's dotnetfiddle): 安德鲁的答案是正确的,如果要命名分组然后用名称替换(从安德鲁的dotnetfiddle扩展而来),这是您的处理方法:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string result = Regex.Replace("This is a test to see if DOMAIN gets replaced properly. DOMAIN", "(?<myName>DOMAIN)", "<a>${myName}</a>");

        result.Dump();
    }
}

Output: 输出:

This is a test to see if <a>DOMAIN</a> gets replaced properly. <a>DOMAIN</a>

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

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