Regex多个表达式获取重复项C#

Regex多个表达式获取重复项C#,c#,regex,string,list,csv,C#,Regex,String,List,Csv,我在c#中使用一个字符串列表,其中包含一个主题列表 例如艺术、科学、音乐 然后用户输入“我想学习科学和艺术” 我想把结果存储到一个变量中,但是我得到了很多重复的结果,比如“science,sciencemusic”(这不是打字错误) 我认为这是因为for-each语句的循环。有没有更简单的方法来实现这一点,或者我的代码中是否有错误?我想不出来 这是我的密码: string input = "I would like to study science and art."; string resul

我在c#中使用一个字符串列表,其中包含一个主题列表

例如艺术、科学、音乐

然后用户输入“我想学习科学和艺术”

我想把结果存储到一个变量中,但是我得到了很多重复的结果,比如“science,sciencemusic”(这不是打字错误)

我认为这是因为for-each语句的循环。有没有更简单的方法来实现这一点,或者我的代码中是否有错误?我想不出来

这是我的密码:

string input = "I would like to study science and art.";
string result = "";

foreach (string sub in SubjectsClass.SubjectsList)
{
    Regex rx = new Regex(sub, RegexOptions.IgnoreCase);

    MatchCollection matches = rx.Matches(input);

    foreach (Match match in matches)
    {
        result += match.Value;
    }
}
subjects类函数“SubjectsList”从CSV文件中读取,其中只有随机主题的单词:

CSV文件:

计算 英语 数学 艺术 科学类 工程

private list<string> subjects = new list<string>();

//Read data from csv file to list...

public list<string>SubjectsList
{
   get { return subjects; }
{
如果我改变:

result += match.Value;

我有很多空间


编辑:我应该提到,此代码在WPF c#按钮上运行,然后显示结果。

使用您的代码,并使用以下测试数据:

List<string> subjects = new List<string>{"Science", "Art", "Maths"};
string input = "I would like to study science and art.";

是否将此结果+=匹配。值+“”;仅当match.Success时,例如:if(match.Success){result+=match.Value+“”;}您的代码有点不完整,很难重现行为或跟踪问题。但是我可能会检查你的循环-看起来它在同一个地方经过了好几次。您可能还应该查看您的表达式-它可能创建了不正确的匹配项(超出了您的预期)…如果(input.Contains(sub))result+=sub,为什么不执行
if(input.Contains(sub))在你的循环中?我只是在输入上运行了你的代码
“art science”
,得到了结果
“artscience”
,而不是你在问题中所说的
“ArtScienceArtScience”
。请确保您提供了足够的代码,以便我可以复制/粘贴/运行您的代码并获得您得到的结果。我们需要一个。我刚刚尝试了你的建议,得到了输入“computing”和结果“computing computing”。正如其他评论所说,这不是你发布的代码所做的。您对结果字符串的声明是否与执行循环的代码分开,以便在不将结果值重置为空的情况下多次调用该字符串,或者主题是否在SubjectsClass.SubjectsList集合中出现多次?
result += match.Value + " ";
List<string> subjects = new List<string>{"Science", "Art", "Maths"};
string input = "I would like to study science and art.";
foreach (Match match in matches)
{
       if (!string.IsNullOrEmpty(match.Value))
       {
            result += match.Value + " ";
       }
}