【问题标题】:Finding Patterns in Lists of Strings and Identifying Groups在字符串列表中查找模式并识别组
【发布时间】:2016-06-21 20:42:17
【问题描述】:

我正在寻找在不知道确切字符串的情况下识别组的方法。字符串可能因列表而异,但通过查看模式的重复是显而易见的。我从来没有使用过 REGEX 表达式,但只是没有开始使用它们,我觉得这比看起来更难。

1区

Zone1ModuleA

Zone1ModuleB

Zone1ModuleAWheel1

Zone1ModuleAWheel2

Zone1ModuleBWheel1

Zone1ModuleBWheel2

2区

Zone2ModuleA

Zone2ModuleB

Zone2ModuleAWheel1

Zone2ModuleAWheel2

Zone2ModuleBWheel1

Zone2ModuleBWheel2

该列表将包含这些模式的更大列表。这些名称将来可能会更改,因此我希望能够识别该模式。最终结果将匹配所有 ZoneModuleAModuleBModuleAWheel1...等等。我正在研究 REGEX 教程,希望有任何帮助!谢谢

【问题讨论】:

    标签: c# regex string c#-4.0 pattern-matching


    【解决方案1】:

    我不知道,如果这是你想要达到的,你可以试试这个:

    void Main()
    {
        var regex = new Regex(@"[A-Z][^A-Z]*[AB]?");
        var lines = linesInFile
            .Replace("\\r", "")
            .Split(new[] { '\n' })
            .Where(i => !string.IsNullOrEmpty(i));
    
        var listOfTokens = new List<string>();
    
        foreach (var line in lines)
        {
            foreach (Match match in regex.Matches(line))
            {
                var value = match.Value;
                if (!listOfTokens.Contains(value))
                {
                    listOfTokens.Add(value);
                }
            }
        }
    
        listOfTokens.Dump();
    }
    
    // Define other methods and classes here
    
    private string linesInFile = @"Zone1
    Zone1ModuleA
    Zone1ModuleB
    Zone1ModuleAWheel1
    Zone1ModuleAWheel2
    Zone1ModuleBWheel1
    Zone1ModuleBWheel2
    Zone2
    Zone2ModuleA
    Zone2ModuleB
    Zone2ModuleAWheel1
    Zone2ModuleAWheel2
    Zone2ModuleBWheel1
    Zone2ModuleBWheel2";
    

    【讨论】:

    • 感谢您的帮助,我找到了查看名称的其他方法,但仍然在项目的另一部分使用了非常相似的解决方案。
    猜你喜欢
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    相关资源
    最近更新 更多