【问题标题】:c# wildcard search replace in a stringc# 通配符搜索替换字符串
【发布时间】:2014-02-11 07:53:13
【问题描述】:

我可以进行搜索,但不知道如何进行替换。我有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 "";
    }

【问题讨论】:

    标签: c# regex search replace wildcard


    【解决方案1】:
    Regex regex = new Regex(pattern);
    string output = regex.Replace(input, replacement);
    

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

    【讨论】:

    • 您好 BenM,感谢您的帮助。它部分有效,当我使用您的代码时,实际值为“/company-info/*abc”,它包含通配符吗?请指教。
    猜你喜欢
    • 1970-01-01
    • 2011-08-16
    • 2010-09-10
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多