【问题标题】:Split a string after reading square brackets in c# [duplicate]在c#中读取方括号后拆分字符串[重复]
【发布时间】:2017-08-29 05:13:35
【问题描述】:
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string new = test.Trim("[");

我想要输出"AccoutNumber"。 我已经尝试了以下代码,但没有得到想要的结果:

string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[');
string newvalue = test[1];

【问题讨论】:

    标签: c#


    【解决方案1】:

    只需使用带有两个分隔符的Split

    string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[', ']');
    string newvalue = test[1];
    

    【讨论】:

      【解决方案2】:

      你也可以使用正则表达式:

      string test = "Account.Parameters[\"AccountNumber\"].Caption";
      var match = System.Text.RegularExpressions.Regex.Match(test, ".*?\\.Parameters\\[\"(.*?)\"]");
      if (match.Success)
      {
          Console.WriteLine(match.Groups[1].Value);
      }
      

      .*? 是一个非贪婪的通配符捕获,所以它会匹配你的字符串直到它到达下一部分(在我们的例子中,它会停在.Parameters[",匹配字符串,然后在"]

      它将匹配.Parameters["..."].,并提取"..."部分。

      【讨论】:

        【解决方案3】:

        您可以对该字符串进行拆分...

        string test = "Account.Parameters[\"AccountNumber\"].Caption";
        string output = test.Split('[', ']')[1];
        Console.WriteLine(output);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-01
          • 2010-09-21
          相关资源
          最近更新 更多