【问题标题】:how to manipulate string which contains different pattern in C#?如何在 C# 中操作包含不同模式的字符串?
【发布时间】:2013-02-10 12:22:48
【问题描述】:

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

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

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

如何做到这一点?

【问题讨论】:

  • 您能否举例说明如何重新计算 { } 的内容?

标签: c# string


【解决方案1】:

你可以试试正则表达式。具体来说,使用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 来处理字符串。

【讨论】:

  • 我正在尝试您的解决方案。但它不工作。正则表达式有问题。
  • @Priyanka:很抱歉:我刚刚更正了正则表达式。
【解决方案2】:

你可以用'{'和'}'分割字符串,然后确定内容。

但我认为更好的方法是按索引查找字符,然后您知道一对或大括号的起始索引和结束索引,这样您就可以用替换的占位符重建字符串。

但最好的方法可能是使用 Regex.Replace 但这只会有助于用您想要的值替换占位符,但我认为您的要求是还解析大括号内的文本并基于该值选择被插入,所以这可能无法正常工作。 Find and Replace a section of a string with wildcard type search

【讨论】:

    【解决方案3】:

    您可以使用Regex.Replace Method (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];
        }
    }
    

    【讨论】:

      【解决方案4】:

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

      例如

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

      【讨论】:

        猜你喜欢
        • 2014-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 2021-01-09
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        相关资源
        最近更新 更多