【问题标题】:What's the best way to acquire a list of strings that match a string inside a string, by looking through a string list?通过查看字符串列表来获取与字符串中的字符串匹配的字符串列表的最佳方法是什么?
【发布时间】:2020-10-05 22:48:44
【问题描述】:

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

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 或 Regex 的简单方法?

【问题讨论】:

  • 您想要重叠匹配吗?例如,如果 matches"hello world", "ello"。而text"hello world!"
  • 你尝试了什么,你在哪里挣扎?请出示您的代码。以“什么是最好的方法”开头的问题往往是题外话。如果您对代码改进有任何疑问,请使用 SOs 姐妹板Codereview
  • string[] matches = Regex.Matches(text, @"\b\{[A-Z]\}\b").Cast<Match>().Select(m => m.Value).ToArray();? Regex 和 Linq
  • @Sweeper:没有重叠,但我的匹配应该保证不重叠,它们是独一无二的。
  • @DmitryBychenko:我刚试过,但我得到了 0 个匹配项。

标签: c# arrays .net regex linq


【解决方案1】:

通过首先使用Select Escapeing matches 中的每个元素,然后使用Joining | 构造正则表达式。之后,获取正则表达式的MatchestextSelect Values:

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

【讨论】:

    【解决方案2】:

    假设 {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}
    

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

    编辑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 "}" 
    

    【讨论】:

    • 谢谢它的工作,但是否可以让正则表达式匹配 {} 之间的任何内容,而不是单个字符?有时我也有 {ABC}。
    • @Joan Venge:只需将 pattern 更改为 .Matches(text, @"\{[A-Z]+\}");注意+ 表示一个或多个大写字母
    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2022-01-21
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多