【发布时间】:2014-02-11 07:53:13
【问题描述】:
我可以进行搜索,但不知道如何进行替换。我有redirectFrom 和redirectTo 通配符模式设置,如下代码所示。对于给定的输入,我需要给定的期望值。任何帮助或建议将不胜感激。非常感谢。
using System.Text.RegularExpressions;
class Program
{
const string redirectFrom = "/info/*";
const string redirectTo = "/company-info/*";
const string input = "/info/abc";
const string expected = "/company-info/abc";
static void Main(string[] args)
{
var pattern = redirectFrom.Replace("*", ".*?");
pattern = pattern.Replace(@"\", @"\\");
pattern = pattern.Replace(" ", @"\s");
var regex = new Regex(pattern, RegexOptions.None);
if (regex.IsMatch(input))
{
Console.WriteLine("Match");
var replaceregex = new Regex(pattern, RegexOptions.None);
string result = replaceregex.Replace(input, new MatchEvaluator(Program.TransformSourceUrl));
}
else
{
Console.WriteLine("No Match");
}
Console.ReadKey();
}
private static string TransformSourceUrl(Match m)
{
int matchCount = 0;
while (m.Success)
{
Console.WriteLine("Match" + (++matchCount));
for (int i = 1; i <= 2; i++)
{
Group g = m.Groups[i];
Console.WriteLine("Group" + i + "='" + g + "'");
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
System.Console.WriteLine("Capture" + j + "='" + c + "', Position=" + c.Index);
}
}
m = m.NextMatch();
}
return "";
}
【问题讨论】:
标签: c# regex search replace wildcard