【发布时间】:2025-12-09 22:40:01
【问题描述】:
我正在尝试在大约 50 000 个字符串的大列表中找到相等的子字符串,这样很好:
var results = myList.FindAll(delegate (string s) { return s.Contains(myString); });
但它也会查找包含部分单词的子字符串,例如,如果我正在查找“you do”,它还会发现额外的“you dont”,因为包含“you do..”。
所以,this answer to my previous question 应该可以按我的需要工作,但我不确定如何从特定代码的正则表达式匹配中获取字符串列表:
foreach (string phrase in matchWordsList)
{
foreach (string str in bigList)
{
string[] stringsToTest = new[] { phrase };
var escapedStrings = stringsToTest.Select(s => Regex.Escape(s));
var regex = new Regex("\\b(" + string.Join("|", escapedStrings) + ")\\b");
var matches = regex.Matches(str);
foreach (string result in matches) /// Incorrect: System.InvalidCastException
{
resultsList.Add(result);
}
}
}
从matches直接获取字符串到list会抛出异常:
发生了“System.InvalidCastException”类型的未处理异常 在test.exe中
附加信息:无法转换类型的对象 'System.Text.RegularExpressions.Match' 输入 'System.String'。
所以,我想弄清楚,热转换var matches = regex.Matches(str); 到列表
【问题讨论】:
-
列表应该包含什么?
-
@John
resultsList必须为matchWordsList的每个短语的每个bigList字符串添加matches的结果 -
这是错误的:foreach(字符串结果匹配)。 Matches 返回 MatchCollection 而不是字符串。我总是告诉人们只在必要时使用 var。你应该使用:MatchCollection matches = regex.Matches(input, pattern);然后编译器会发现错误而不是得到运行时错误。
标签: c# regex linq substring contains