从字符串中获取符号数组

时间:2011-07-12 07:40:06

标签: c# regex

我在curlies中有一个带有文本的字符串,如下所示:

{field1}-{field}+{field3}Anthing{field4}  

我需要从中获得这样的数组:

['field1', 'field2', 'field3', 'field4']

有没有办法在c#中使用正则表达式?

2 个答案:

答案 0 :(得分:3)

您可以使用Split和Linq:

string[] words = s.Split('+')
                  .Select(word => word.Substring(1, word.Length - 2))
                  .ToArray();

或者,您可以使用简单的正则表达式匹配{...}令牌:

MatchCollection matches = Regex.Matches(s, @"\{(\w*)\}");
string[] words = matches.Cast<Match>()
                        .Select(m => m.Groups[1].Value)
                        .ToArray();

\w*只会匹配字母数字字符,您可能希望将其替换为[^}]*.*?

答案 1 :(得分:1)

像这样? ↓

  static void Main(string[] args)
    {
        string from = "{field1}+{field2}+{field3}";
        string[] to = from.Split("{}+".ToCharArray() , StringSplitOptions.RemoveEmptyEntries).ToArray();

        foreach (var x in to)
            Console.WriteLine(x);

        Console.ReadKey();
    }

FOR EDIT

  • 使用“{field1} - {field} + {field3} Anthing {field4}”解决问题

    static void Main(string[] args)
    {
        string f = "{field1}-{field}+{field3}Anthing{field4} ";
        List<string> lstPattern = new List<string>();
        foreach (Match m in Regex.Matches(f, "{.*?}"))
        {
            lstPattern.Add(m.Value.Replace("{","").Replace("}",""));
        }
    
        foreach (var p in lstPattern)
            Console.WriteLine(p);
    
    }