检查字符串是否在Enumerable.Range筛选器列表中包含匹配项 [英] Check if String Contains Match in Enumerable.Range Filter List

查看:86
本文介绍了检查字符串是否在Enumerable.Range筛选器列表中包含匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查字符串是否包含列表中的单词或数字,并将其从字符串中删除.

I want to check if a string contains a word or number from a list and remove it from the string.

我想使用Enumerable.Range()创建过滤器列表并使用它来过滤许多不同的字符串.

I want to use Enumerable.Range() to create the filter list and use it to filter many different strings.

我正在尝试结合之前的两个答案:
https://stackoverflow.com/a/49733139/6806643
https://stackoverflow.com/a/49740832/6806643

I'm trying to combine two previous answers:
https://stackoverflow.com/a/49733139/6806643
https://stackoverflow.com/a/49740832/6806643

我要过滤的句子:

这是A05B09你好02100测试

This is a A05B09 hello 02 100 test


过滤器

A00B00-A100B10001-100000-100hello

应阅读:

这是一个测试

This is a test


旧方式
For Loop-作品
http://rextester.com/BJL70824


Old Way
For Loop - Works
http://rextester.com/BJL70824

新方法
Enumerable Range List-不起作用
http://rextester.com/ZSCM64375

New Way
Enumerable Range List - Does not work
http://rextester.com/ZSCM64375

C#

List<List<string>> filters = Enumerable.Range(0, 101)
       .SelectMany(a => Enumerable.Range(0, 101).Select(b => "A{0:00}B{1:00}"))
       .Select(i => Enumerable.Range(0, 10).Select(c => string.Empty).ToList())
           .SelectMany(a => Enumerable.Range(0, 101).Select(b => "{0:000}"))
           .SelectMany(a => Enumerable.Range(0, 101).Select(b => "{0:00}"))
           .SelectMany(a => Enumerable.Range(0, 1).Select(b => "hello"))
           .ToList();

List<string> matches = new List<string>();

// Sentence
string sentence = "This is a A05B09 hello 02 100 test";
string newSentence = string.Empty;


// Find Matches
for (int i = 0; i < filters.Count; i++)
{
    // Add to Matches List
    if (sentence.Contains(filters[i].ToString()))
    {
        matches.Add(filters[i]);
    }
}

// Filter Sentence
newSentence = Regex.Replace(
    sentence
,   @"(?<!\S)(" + string.Join("|", matches) + @")(?!\S)"
,   ""
,   RegexOptions.IgnoreCase
);

// Display New Sentence
Console.WriteLine(newSentence);

推荐答案

我认为创建所有可能组合的列表是一种非常糟糕的方法.您正在创建庞大的列表,这将使您的进程使用大量RAM,并且没有任何正当理由就会非常慢.为什么不仅仅创建一个好的Regex?例如,使用此表达式,您将获得所需的字符串:

I think creating a list of all possible combinations is a very bad approach. You are creating huge lists which will make your process use a lot of RAM and be very slow without any good reason. Why not just create a good Regex? For example, with this expression, you get your desired string:

\b(A\d\dB\d\d|A100B100|0?\d\d|100|hello)\b\s*

那是假设您不想替换A101B101123之类的东西.

That is assuming you don't want to replace stuff like A101B101 or 123.

如果您也想替换它们,则正则表达式会更简单:

If you want to replace those as well, the regex is a bit simpler:

\b(A\d\d\d?B\d\d\d?|\d\d\d?|hello)\b\s*

这篇关于检查字符串是否在Enumerable.Range筛选器列表中包含匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆