使用正则表达式替换字符串中的类属性

本文关键字:属性 字符串 正则表达式 替换 | 更新日期: 2023-09-27 18:28:32

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

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

我想捕获诸如"@Customer.Name","@Order.Date"之类的类属性的出现,并使用反射将它们替换为其值。

有没有人可以帮助我,请(请原谅我的英语...

使用正则表达式替换字符串中的类属性

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

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

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

你真的想走这么复杂的路吗?

为什么只是没有像这样的字符串

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)

除了关于为什么正则表达式可能不是正确解决方案的评论之外,如果您确实需要一个正则表达式(因为您需要它更加动态,例如,可能会处理多个模板(,如下所示:

@'w+'.?'w+

应该做这个伎俩。

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

你可以像这样使用它:

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

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