用值替换正则表达式中的命名组

Tom*_*cek 9 c# regex

我想使用与string.Format相同的正则表达式.我会解释

我有:

string pattern = "^(?<PREFIX>abc_)(?<ID>[0-9])+(?<POSTFIX>_def)$";
string input = "abc_123_def";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
string replacement = "456";
Console.WriteLine(regex.Replace(input, string.Format("${{PREFIX}}{0}${{POSTFIX}}", replacement)));
Run Code Online (Sandbox Code Playgroud)

这有效,但我必须为regex.Replace提供"输入".我不要那个.我想使用模式进行匹配,但也使用与字符串格式相同的方式创建字符串,用值替换命名组"ID".那可能吗?

我正在寻找类似的东西:

string pattern = "^(?<PREFIX>abc_)(?<ID>[0-9])+(?<POSTFIX>_def)$";
string result = ReplaceWithFormat(pattern, "ID", 999);
Run Code Online (Sandbox Code Playgroud)

结果将包含"abc_999_def".怎么做到这一点?

use*_*787 17

对的,这是可能的:

public static class RegexExtensions
{
    public static string Replace(this string input, Regex regex, string groupName, string replacement)
    {
        return regex.Replace(input, m =>
        {
            return ReplaceNamedGroup(input, groupName, replacement, m);
        });
    }

    private static string ReplaceNamedGroup(string input, string groupName, string replacement, Match m)
    {
        string capture = m.Value;
        capture = capture.Remove(m.Groups[groupName].Index - m.Index, m.Groups[groupName].Length);
        capture = capture.Insert(m.Groups[groupName].Index - m.Index, replacement);
        return capture;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

Regex regex = new Regex("^(?<PREFIX>abc_)(?<ID>[0-9]+)(?<POSTFIX>_def)$");

string oldValue = "abc_123_def";
var result = oldValue.Replace(regex, "ID", "456");
Run Code Online (Sandbox Code Playgroud)

结果是:abc_456_def

  • 你必须明白他想要什么,而不是抨击他的错误.看看标题:"在regex中用值取代命名组",看看你的答案,命名组在哪里?看看他的样本:"ReplaceWithFormat(pattern,"ID",999);".他显然想用999替换当前的"ID".看看他的预期结果:"abc_999_def".他希望用"999"替换"abc_123_def"中的命名组"ID"并接收"abc_999_def".说这是不可能的根本没有帮助.您的示例代码也不能满足他的需求. (9认同)
  • 不要让你的吉米沙哑。 (2认同)

Guf*_*ffa 13

不,如果不提供输入,则无法使用正则表达式.它必须有一些东西可以使用,模式不能向结果添加任何数据,一切都必须来自输入或替换.

使用String.Format的Intead,你可以使用后面的一个看,并指望前面指定"abc_"和"_def"之间的部分,并替换它:

string result = Regex.Replace(input, @"(?<=abc_)\d+(?=_def)", "999");
Run Code Online (Sandbox Code Playgroud)

  • 为什么选择downvote?如果你不解释你认为错误的东西,它就无法改善答案. (11认同)

Jus*_*tin 5

user1817787回答中存在问题,我必须对ReplaceNamedGroup功能进行如下修改。

private static string ReplaceNamedGroup(string input, string groupName, string replacement, Match m)
{
    string capture = m.Value;
    capture = capture.Remove(m.Groups[groupName].Index - m.Index, m.Groups[groupName].Length);
    capture = capture.Insert(m.Groups[groupName].Index - m.Index, replacement);
    return capture;
}
Run Code Online (Sandbox Code Playgroud)