【问题标题】:Regex Multiple Expressions Getting Duplicates C#正则表达式多个表达式获取重复 C#
【发布时间】:2016-04-12 20:03:22
【问题描述】:

我在 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;
    }
}

主题类函数“SubjectsList”是从 CSV 文件中读取的,其中只有随机主题的单词:

CSV 文件:

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

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

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

public list<string>SubjectsList
{
   get { return subjects; }
{

目前我得到的输出是这样的:

"input": "art science",
"Subject": "artscienceartscienceartscience"

如果我改变:

result += match.Value;

到

result += match.Value + " ";

我有很多空间。

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

【问题讨论】:

  • 做这个结果 += match.Value + " "';仅当 match.Success 时,如:if (match.Success) { result += match.Value + " "; }
  • 您的代码有点不完整,很难重现该行为或跟踪问题。但我可能会检查你的循环——看起来它在同一个地方经过了好几次。您可能还应该查看您的表达式 - 它可能会创建不正确的匹配项(超出您的预期)...
  • 你为什么不在你的循环中做一个if(input.Contains(sub)) result+=sub;?
  • 我刚刚在输入 "art science" 上运行了您的代码并得到了结果 "artscience",而不是您在问题中所说的 "artscienceartscienceartscience"。您能否确保提供足够的代码,以便我可以复制/粘贴/运行您的代码并获得您得到的结果。我们需要一个minimal reproducible example。

标签: c# regex string list csv


【解决方案1】:

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

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 + " ";
       }
}

【讨论】:

  • 我刚刚尝试了你的建议,得到输入“computing”,结果为“computing computing”。
  • 正如其他评论者所说,这不是您发布的代码的作用。您对结果字符串的声明是否与执行循环的代码分开,以便在不将结果值重置为空的情况下多次调用它,或者主题是否在 SubjectsClass.SubjectsList 集合中出现多次?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多