如何使用C#从下面的字符串中提取键

时间:2019-03-20 10:06:07

标签: c# string

输入查询

 select * from mytable where projectname = __$ProjectName$__ and  projectid = __$ProjectId$__ and env = __$EnvType$__

我希望在下面的输出中显示字符串(List<string>)的列表。(双下划线+美元+“字符串” +美元+双下划线) 语言:C#

 __ $ProjectName$__
 __ $ProjectId$__
 __ $EnvType$__

3 个答案:

答案 0 :(得分:5)

使用Linq:

List<string> output = input.Split(' ').Where(x => x.StartsWith("__$") && x.EndsWith("$__")).ToList();

答案 1 :(得分:3)

尝试正则表达式;如果键

  1. __$开始
  2. 包含 标识符(以字母A..Za..z开头,可以包含字母或\和数字A..Z,{ {1}},a..z
  3. 0..9
  4. 结尾

要匹配的模式是$__

代码:

__\$[A-Za-z]+[A-Za-z0-9]*\$__

结果:

using System.Text.RegularExpressions;

...

string source = 
  "select * from mytable where projectname = __$ProjectName$__ and  projectid = __$ProjectId$__ and env = __$EnvType$__";

List<string> keys = Regex
  .Matches(source, @"__\$[A-Za-z]+[A-Za-z0-9]*\$__")
  .OfType<Match>()
  .Select(match => match.Value)
  .ToList();

Console.Write(string.Join(Environment.NewLine, keys));

答案 2 :(得分:1)

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var expression = @"select * from mytable where projectname = __$ProjectName$__ and  projectid = __$ProjectId$__ and env = __$EnvType$__";

            var output = new Regex(@"__\$[^\s]+?\$__")
                .Matches(expression)
                .Cast<Match>()
                .Select(m => m.Value)
                .ToList();

            output.ForEach(Console.WriteLine);
        }
    }
}