[英]how to extract keys from the string below using c#
输入查询
select * from mytable where projectname = __$ProjectName$__ and projectid = __$ProjectId$__ and env = __$EnvType$__
我想要下面的输出的字符串List<string>
( List<string>
)。(双下划线+美元+“字符串” +美元+双下划线)语言:C#
__ $ProjectName$__
__ $ProjectId$__
__ $EnvType$__
使用Linq:
List<string> output = input.Split(' ').Where(x => x.StartsWith("__$") && x.EndsWith("$__")).ToList();
尝试正则表达式 ; 如果键
__$
A..Z
, a..z
,可以包含字母或\\和数字A..Z
, a..z
, 0..9
) $__
结尾 匹配的模式是__\\$[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));
结果:
__$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.