c#通配符搜索替换为字符串

时间:2014-01-21 15:51:26

标签: c# regex search replace wildcard

我能够进行搜索,但无法弄清楚如何进行替换。我有redirectFromredirectTo通配符模式设置,如下面的代码所示。对于给定的输入,我需要给定的期望值。任何帮助或建议将受到高度赞赏。非常感谢。

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 "";
    }

1 个答案:

答案 0 :(得分:1)

Regex regex = new Regex(pattern);
string output = regex.Replace(input, replacement);

http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx