简体   繁体   English

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

[英]how to extract keys from the string below using c#

Input query 输入查询

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

I want list of string ( List<string> ) as output below.(double underscore+dollar+"string"+dollar+double underscore) Language: C# 我想要下面的输出的字符串List<string>List<string> )。(双下划线+美元+“字符串” +美元+双下划线)语言:​​C#

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

使用Linq:

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

Try regular expressions ; 尝试正则表达式 ; if key 如果键

  1. Starts from __$ 起始__$
  2. Contains identifier (which starts from letter A..Z , a..z , can contain letters or\\and digits A..Z , a..z , 0..9 ) 包含 标识符 (以字母A..Za..z ,可以包含字母或\\和数字A..Za..z0..9
  3. Ends with $__ $__ 结尾

the pattern to match is __\\$[A-Za-z]+[A-Za-z0-9]*\\$__ 匹配的模式是__\\$[A-Za-z]+[A-Za-z0-9]*\\$__

Code: 码:

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));

Outcome: 结果:

__$ProjectName$__
__$ProjectId$__
__$EnvType$__
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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM