我想检查字符串是否包含列表中的单词或数字并将其从字符串中删除。
我想使用 Enumerable.Range()
创建过滤器列表并使用它来过滤许多不同的字符串。
我正在尝试结合之前的两个答案:
https://stackoverflow.com/a/49733139/6806643
https://stackoverflow.com/a/49740832/6806643
我要过滤的句子:
This is a A05B09 hello 02 100 test
过滤
A00B00-A100B100
、01-100
、000-100
、你好
应该阅读:
This is a test
老方法
For 循环
- 有效
http://rextester.com/BJL70824
新方式
可枚举范围列表
- 不起作用
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 并且在没有任何充分理由的情况下变得非常慢。为什么不直接创建一个好的正则表达式呢?例如,使用此表达式,您将获得所需的字符串:
\b(A\d\dB\d\d|A100B100|0?\d\d|100|hello)\b\s*
这是假设您不想替换诸如 A101B101
或 123
之类的内容。
如果您也想替换它们,则正则表达式更简单:
\b(A\d\d\d?B\d\d\d?|\d\d\d?|hello)\b\s*
关于c# - 检查字符串是否包含 Enumerable.Range 过滤器列表中的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49742572/