使用Regex替换字符串中的类属性

时间:2014-10-31 13:27:31

标签: c# regex

请,我想替换字符串中的类属性(或字段),我想使用正则表达式,但我不熟悉正则表达式。 字符串示例:

string Source = "Dear @Customer.Civility, @Customer.Name @Customer.Surname\n\n " +
"About your bill dated @Order.Date..."

我想要了解类属性的出现,例如" @ Customer.Name" ," @ Order.Date"并使用反射将其替换为其值。

是否有AnyOne帮助我,请(原谅我的英语......)

3 个答案:

答案 0 :(得分:3)

这实际上是一项有趣的挑战。我使用了马特的正则表达式。

var customer = new Customer() {  Civility = "Mr.", Name = "Max", Surname = "Mustermann" };
var order = new Order();
string Source = "Dear @Customer.Civility, @Customer.Name @Customer.Surname\n\n About your bill dated @Order.Date...";
string s = BringTheMash(Source, new { Customer = customer, Order = order });

Console.WriteLine(s);


private static string BringTheMash(string format, object p)
{
    string result = format;
    var regex = new Regex(@"@(?<object>\w+)\.?(?<property>\w+)");
    foreach (Match m in regex.Matches(format))
    {
        var obj = m.Groups[1].ToString();
        var prop = m.Groups[2].ToString();

        var parameter = p.GetType().GetProperty(obj).GetValue(p);
        var value = parameter.GetType().GetProperty(prop).GetValue(parameter);

        result = result.Replace(m.Value, value.ToString());
    }

    return result;
}

我没有添加任何异常处理,如果对象没有必需的属性,就会发生这种情况。

答案 1 :(得分:2)

你真的想要这么复杂吗?

为什么没有像

这样的字符串
string Source = "Dear {0}, {1} {2}\n\n " + "About your bill dated {3}..."

以后再格式化

string result = string.Format(Source, 
    Customer.Civility, 
    Customer.Name, 
    Customer.Surname, 
    Order.Date)

答案 2 :(得分:2)

除了关于为什么正则表达式可能不是正确解决方案的评论之外,如果你确实需要一个正则表达式(因为你需要它更具动态性,可能需要处理几个模板),例如:

@\w+\.?\w+

应该做的伎俩。

它匹配文字@后跟一个或多个单词字符(\w是类[A-Za-z0-9_]的简写,即所有字母,数字和下划线,应该覆盖你),然后是可选的.(如果您希望它是非可选的,只需删除?),然后是一个或多个单词字符。

你可以像这样使用它:

var regex = new Regex(@"@\w+\.?\w+");

string Source = "Dear @Customer.Civility, @Customer.Name @Customer.Surname\n\n " +
    "About your bill dated @Order.Date...";

foreach(Match m in regex.Matches(Source)) 
{
    // do whatever processing you want with the matches here.
    Console.WriteLine(string.Format("{0}:{1}",m.Index,m.Value));   
}

日志:

5:@Customer.Civility
25:@Customer.Name
40:@Customer.Surname
82:@Order.Date

使用索引和匹配文本,您应该拥有进行替换所需的一切。

如果您想更轻松地从匹配中提取对象和属性,可以在正则表达式中使用分组。像这样:

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

string Source = "Dear @Customer.Civility, @Customer.Name @Customer.Surname\n\n " +
    "About your bill dated @Order.Date...";

foreach(Match m in regex.Matches(Source)) 
{
    Console.WriteLine(string.Format("Index: {0}, Object: {1}, Property: {2}",
                      m.Index,m.Groups["object"],m.Groups["property"]));
}

将记录:

Index: 5, Object: Customer, Property: Civility
Index: 25, Object: Customer, Property: Name
Index: 40, Object: Customer, Property: Surname
Index: 82, Object: Order, Property: Date

所以现在你已经确定了索引,从中获取替换所需的对象以及从该对象获取所需的属性。