0
我能夠做一個搜索,但無法弄清楚如何做替換。我在代碼中設置了redirectFrom
和redirectTo
通配符模式,如下所示。對於給定的輸入,我需要給定的期望值。任何幫助或建議將不勝感激。非常感謝。c#通配符搜索替換字符串
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 "";
}
嗨BenM,感謝您的幫助。它部分工作,當我使用你的代碼時,實際值是「/ company-info/* abc」,它包含通配符?請指教。 – user1809943