替换为字符串中给定模式的值

时间:2022-04-01 21:25:38

Given a file with this format

给定具有此格式的文件

// Colour
$primary-colour: if(@Model.PrimaryColour, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on

I'm trying to replace the @Model.Whatever based on a dictionary with would be something like this

我正在尝试替换@ Model.Whatever基于字典会是这样的

var dictionary = new Dictionary<string, string>
{
    {"primaryColour", "blue"},
    {"secondaryColour", "red"}
};

But I'm struggling to find a way to so.

但我正在努力找到一条路。

I was thinking of doing something like this:

我在考虑做这样的事情:

private static String Replace(String str)
{
    var dictionary = new Dictionary<string, string>
    {
        {"primaryColour", "blue"},
        {"secondaryColour", "red"}
    };

    string variableValue;
    string pattern = @"@Model.(?<name>\w)";
    dictionary.TryGetValue(FirstCharacterToLower("${name}"), out variableValue);
    var replacePattern = String.Format("{0}", variableValue);
    return Regex.Replace(str, pattern, replacePattern, RegexOptions.IgnoreCase);
}

private static string FirstCharacterToLower(string str)
{
    Console.WriteLine(str);
    if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
        return str;

    return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}

But what I'm passing to the FirstCharacterToLower is just a string {name} and I'm stuck there. Can't think of a way to do it.

但是我传递给FirstCharacterToLower的只是一个字符串{name}而且我被困在那里。想不出办法做到这一点。

Any idea where to go from here?

不知道从哪里开始?

Thanks

谢谢

Edit: Based on sln comment I made this and it works

编辑:基于sln评论我做了这个,它的工作原理

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        var input = @"
            // Colour
            $primary-colour: if(@Model.PrimaryColour, @Model.PrimaryColour, #afd05c);
            $secondary-colour: if(@Model.SecondaryColour, @Model.SecondaryColour, #323f47);";

        Console.WriteLine(Replace(input));
    }

    private static String Replace(String str)
    {
        var dictionary = new Dictionary<string, string>
        {
            {"primaryColour", "blue"},
            {"secondaryColour", "red"}
        };

        var regex = new Regex(@"@Model\.(?<name>\w+)");

        var output = regex.Replace(str, v => 
            {
                string outVariable;
                dictionary.TryGetValue(GetNameOfVariable(v.Groups["name"].Value), out outVariable);
                return outVariable;
            });

        return output;
    }

    private static string GetNameOfVariable(string str)
    {
        Console.WriteLine(str);
        if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
            return str;

        return Char.ToLowerInvariant(str[0]) + str.Substring(1);
    }
}

2 个解决方案

#1


1  

As @sln told, you have to use delegate.

正如@sln所说,你必须使用委托。

private static String Replace(String str)
{
    var dictionary = new Dictionary<string, string>
    {
        {"primaryColour", "blue"},
        {"secondaryColour", "red"}
    };

    string pattern = @"@Model\.(?<name>\w+)";
    return Regex.Replace(str, pattern, m => 
        {
            string key = m.Groups["name"].Value;
            key = FirstCharacterToLower(key);
            string value = null;
            if (dictionary.TryGetValue(key, out value))
                return value;
            else
                return m.Value;
        });
}

#2


1  

You'd be better off describing a general regex that matches all your
keys. Then using a delegate replacement.

你最好描述一个匹配所有键的一般正则表达式。然后使用委托替换。

var dictionary = new Dictionary<string, string>
{
    {"primarycolour", "blue"},
    {"secondarycolour", "red"}
};

string line_original =
@"
// Colour
$primary-colour: if(@Model.PrimaryColour, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on
";

Regex RxColors = new Regex( @"@Model\.(?<name>\w+)" );
string line_new = RxColors.Replace(
    line_original,
    delegate(Match match)
    {
        string outVal;
        if ( dictionary.TryGetValue( match.Groups["name"].Value.ToLower(), out outVal) )
            return outVal;
        return match.Groups[0].Value;
    }
);
Console.WriteLine("New line: \r\n\r\n{0}", line_new );

Output:

输出:

New line:

// Colour
$primary-colour: if(blue, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on

#1


1  

As @sln told, you have to use delegate.

正如@sln所说,你必须使用委托。

private static String Replace(String str)
{
    var dictionary = new Dictionary<string, string>
    {
        {"primaryColour", "blue"},
        {"secondaryColour", "red"}
    };

    string pattern = @"@Model\.(?<name>\w+)";
    return Regex.Replace(str, pattern, m => 
        {
            string key = m.Groups["name"].Value;
            key = FirstCharacterToLower(key);
            string value = null;
            if (dictionary.TryGetValue(key, out value))
                return value;
            else
                return m.Value;
        });
}

#2


1  

You'd be better off describing a general regex that matches all your
keys. Then using a delegate replacement.

你最好描述一个匹配所有键的一般正则表达式。然后使用委托替换。

var dictionary = new Dictionary<string, string>
{
    {"primarycolour", "blue"},
    {"secondarycolour", "red"}
};

string line_original =
@"
// Colour
$primary-colour: if(@Model.PrimaryColour, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on
";

Regex RxColors = new Regex( @"@Model\.(?<name>\w+)" );
string line_new = RxColors.Replace(
    line_original,
    delegate(Match match)
    {
        string outVal;
        if ( dictionary.TryGetValue( match.Groups["name"].Value.ToLower(), out outVal) )
            return outVal;
        return match.Groups[0].Value;
    }
);
Console.WriteLine("New line: \r\n\r\n{0}", line_new );

Output:

输出:

New line:

// Colour
$primary-colour: if(blue, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on