我想使用与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
Guf*_*ffa 13
不,如果不提供输入,则无法使用正则表达式.它必须有一些东西可以使用,模式不能向结果添加任何数据,一切都必须来自输入或替换.
使用String.Format的Intead,你可以使用后面的一个看,并指望前面指定"abc_"和"_def"之间的部分,并替换它:
string result = Regex.Replace(input, @"(?<=abc_)\d+(?=_def)", "999");
Run Code Online (Sandbox Code Playgroud)
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)