繁体   English   中英

通过查看字符串列表来获取与字符串中的字符串匹配的字符串列表的最佳方法是什么?

[英]What's the best way to acquire a list of strings that match a string inside a string, by looking through a string list?

基本上我有一个字符串数组,我用它来匹配单个字符串:

string[] matches = { "{A}", "{B}", "{CC}" };

然后我从这些中查找是否在我的字符串中找到任何这些:

string text = "Lorem Ipsum is {CC} simply dummy text {A} of the {CC} printing and typesetting industry {B}."

在这种情况下,我想要收集的结果数组应该是:

string[] allmatches = { "{CC}", "{A}", "{CC}", "{B}" };

有没有一种简单的方法可以使用 LINQ 或正则表达式来做到这一点?

假设{A}..{Z}是唯一需要的匹配项,我们可以尝试结合Regex和 Linq,例如

  string text = 
    @"Lorem Ipsum is {C} simply dummy text {A} of the {C} printing and typesetting industry {B}.";

  string[] allmatches = Regex
    .Matches(text, @"\{[A-Z]\}")
    .Cast<Match>()
    .Select(m => m.Value)
    //.Where(item => matches.Contains(item)) // uncomment to validate matches
    .ToArray();

我们来看一下:

  Console.Write(string.Join(", ", allmatches));

结果:

  {C}, {A}, {C}, {B}

编辑:取消注释.Where(...)如果您只想要匹配项中的matches[]

编辑 2:如果匹配不需要只包含一个字母,请更改模式:

  .Matches(text, @"\{[A-Z]+\}")    // one or more capital letters
  .Matches(text, @"\{[a-zA-Z]+\}") // one or more English letters
  .Matches(text, @"\{\p{L}+\}")    // one or more Unicode letters
  .Matches(text, @"\{[^}{]+\}")    // one or more characters except "{" and "}" 

通过首先使用Selectmatches中的每个元素进行Escape ,然后使用Join来构造正则| . 之后,获取正则表达式对textMatches项和SelectValue

var regex = string.Join("|", matches.Select(Regex.Escape));
var result = Regex.Matches(text, regex)
            .Cast<Match>()
            .Select(x => x.Value).ToArray();

暂无
暂无

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

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