如何在C#中操作包含不同模式的字符串

本文关键字:模式 字符串 操作包 | 更新日期: 2023-09-27 17:58:12

我有以下类型的字符串格式---

Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}

字符串包含一对具有不同位置的{},并且可以是n次。现在我想用其他字符串替换该对,我将根据{}对之间的字符串来计算这些字符串。

如何做到这一点?

如何在C#中操作包含不同模式的字符串

您可以尝试正则表达式。具体来说,使用MatchEvaluatorRegex.Replace变体应该可以做到这一点。看见http://msdn.microsoft.com/en-US/library/cft8645c(v=vs.80).aspx获取更多信息。

大致如下:

using System;
using System.Text.RegularExpressions;
public class Replacer
{
    public string Replace(string input)
    {
        // The regular expression passed as the second argument to the Replace method
        // matches strings in the format "{value0#value1/value2}", i.e. three strings
        // separated by "#" and "/" all surrounded by braces.
        var result = Regex.Replace(
            input,
            @"{(?<value0>[^#]+)#(?<value1>[^/]+)/(?<value2>[^}]+)}",
            ReplaceMatchEvaluator);
        return result;
    }
    private string ReplaceMatchEvaluator(Match m)
    {
        // m.Value contains the matched string including the braces.
        // This method is invoked once per matching portion of the input string.
        // We can then extract each of the named groups in order to access the
        // substrings of each matching portion as follows:
        var value0 = m.Groups["value0"].Value; // Contains first value, e.g. "Jwala Vora"
        var value1 = m.Groups["value1"].Value; // Contains second value, e.g. "3"
        var value2 = m.Groups["value2"].Value; // Contains third value, e.g. "13"
        // Here we can do things like convert value1 and value2 to integers...
        var intValue1 = Int32.Parse(value1);
        var intValue2 = Int32.Parse(value2);
        // etc.
        // Here we return the value with which the matching portion is replaced.
        // This would be some function of value0, value1 and value2 as well as
        // any other data in the Replacer class.
        return "xyz";
    }
}
public static class Program
{
    public static void Main(string[] args)
    {
        var replacer = new Replacer();
        var result = replacer.Replace("Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}");
        Console.WriteLine(result);
    }
}

该程序将输出Proposal is given to xyz for xyz xyz by xyz

您需要在ReplaceMatchEvaluator方法中提供特定于应用程序的逻辑,以适当地处理value0value1value2。类Replacer可以包含可用于实现ReplaceMatchEvaluator中的替换逻辑的附加成员。通过在Replacer类的实例上调用Replace来处理字符串。

您可以通过"{"answers"}"来拆分字符串,并以此方式确定内容。

但我认为更好的方法是通过索引找到字符,然后你知道一对或大括号的起始索引和结束索引,这样你就可以在替换了占位符的情况下重建字符串。

但最好的方法可能是使用Regex.Replace,但这只会有助于用你想要的值替换占位符,但我认为你的要求是还要解析花括号内的文本,并在此基础上选择要插入的值,所以这可能不太好用。查找字符串的一部分并将其替换为通配符类型搜索

您可以使用Regex.Replace方法(String、String、MatchEvaluator)和{.*?}模式。下面的示例使用字典来替换值,但您可以用自己的逻辑来替换它。

class Program
{
    static Dictionary<string, string> _dict = new Dictionary<string, string>();
    static void Main(string[] args)
    {
        _dict.Add("{Jwala Vora#3/13}","someValue1");
        _dict.Add("{Amazon Vally#2/11}", "someValue2");
        _dict.Add("{1#3/75}", "someValue3");
        _dict.Add("{MdOffice employee#1/1}", "someValue4");
        var input = @"Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}";
        var result = Regex.Replace(input, @"{.*?}", Evaluate);
        Console.WriteLine(result);
    }
    private static string Evaluate(Match match)
    {
        return _dict[match.Value];
    }
}

你不能用string.Format()做点什么吗?

例如

string.Format("Proposal is given to {0} for {1} {2} by {3}", "Jwala Vora", "Amazon Vally", 1, "MdOffice employee");