从列表创建数组的优雅方法是什么

本文关键字:方法 是什么 列表 创建 数组 | 更新日期: 2023-09-27 18:31:03

我有这个字符串:

"(Id=7) OR (Id=6) OR (Id=8)"

从上面的字符串中,我如何创建这样的数组或列表:

"Id=6"
"Id=7"
"Id=8"

从列表创建数组的优雅方法是什么

不使用正则表达式,但使用一些 Linq 你可以写

string test = "(Id=7) OR (Id=6) OR (Id=8)";
var result = test
    .Split(new string[] { " OR "}, StringSplitOptions.None)
    .Select(x => x = x.Trim('(', ')'))
    .ToList();

如果您还需要考虑 AND 运算符的存在或 AND/OR 和条件之间可变数量的空格,那么您可以将代码更改为此代码

string test = "(Id=7) OR (Id=6) OR (Id=8)";
var result = test
    .Split(new string[] { "OR", "AND"}, StringSplitOptions.None)
    .Select(x => x = x.Trim('(', ')', ' '))
    .ToList();

我建议结合正则表达式和LINQ功能:

var result = Regex.Matches(input, @"'(([^()]+)')")
       .Cast<Match>()
       .Select(p => p.Groups[1].Value)
       .ToList();

'(([^()]+)')模式(参见其演示)将匹配所有(...)字符串,并使用组 1(在未转义的(...)内)构建最终列表。

只需抓住火柴

(?<='()[^)]*(?='))

请参阅演示。

https://regex101.com/r/iJ7bT6/18

string strRegex = @"(?<='()[^)]*(?='))";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"(Id=7) OR (Id=6) OR (Id=8)";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
   if (myMatch.Success)
   {
     // Add your code here
  }
}