【问题标题】:I need to do some pattern matching with more than one pattern as input in C#我需要使用多个模式作为 C# 中的输入进行一些模式匹配
【发布时间】:2011-08-28 16:53:39
【问题描述】:

我需要做一些模式匹配来处理问题列表并提出 一些声明将成为解决方案列表的首位。我需要匹配的每个问题 第一个句子以“?”结尾。例如,如果有以下字符串:

input="Which of the following can be aa ... zz?"

然后我需要看看这是否匹配一些预定义的模式,如果匹配,那么我需要填充两个变量。在这个例子中,上面的字符串需要产生以下结果:

string1= "Can be aa ... zz:"
string2= "Cannot be contained aa ... zz:"

源中的文本 aa ... zzz 出现在目标中的位置。

Inputs:

1 - Which of the following can be aa ... zz?
2 - Which of the following are correct?
3 - What will result when aa ... zz?
4 - Which of the following is a aa ... zz?
5 - Which are aa ... zz?
6 - What can be said about aa ... zz:
7 - Which of the following is true?
8 - What will be the result when aa ... zz?

Output 1:

1 - Can be aa ... zz:
2 - Correct:
3 - The following will result::
4 - A aa ... zz
5 - The following are aa ... zz
6 - True statement(s)
7 - True statement(s)
8 - The following will result:

Output 2:

1 - Cannot be aa ... zz:
2 - Incorrect:
3 - The following will not result
4 - Not a aa ... zz:
5 - Are not aa ... zz:
6 - False statement(s)
7 - False statement(s)
8 - The following will not result

我在想我应该将输入模式和输出模式存储在参考数据类中,然后可能是链接和模式匹配的某种组合。

有没有人有什么建议。即使我能看到如何进行一场比赛,那也很好。 如果我有一个示例,那么我可以编写更多代码并从中工作。

什么样的模式? - 模式是文本。因此,例如,我正在查看我的输入字符串是否以“以下哪一项可以”开头并以“?”结尾。

这些问题来自哪里? - 一组有限的问题。如果我找不到匹配项,我会在输出中输入“True”或“False”之类的内容。

【问题讨论】:

  • 什么样的模式?你在用什么,正则表达式?这些问题来自哪里,是一组有限的可能值还是你在解析书籍?更多细节以及您已经处理的任何事情都可能会有所帮助。
  • 感谢您的评论。我在问题中添加了更多注释。希望能帮助到你。我只是在寻找一个简单的建议来帮助我入门。

标签: c# linq


【解决方案1】:

它可以像下面这样建模:

static Tuple<string,string> Match(string question)
{
   //Do the matching and return the string,string tuple where first 
   //string is for output 1 and second for output 2.
}

static Tuple<List<string>,List<string>> GetOutput(List<string> questions)
{
    var r = questions.Select(q => Match(q));
    return new Tuple<List<string>,List<string>(r.Select(t => t.Item1).ToList(), r.Select(t =>  t.Item2).ToList());
}

【讨论】:

  • 但这不只适用于完全匹配吗?我想我需要使用像正则表达式这样的想法,因为我的字符串的“aa ... zz”部分可以是任何序列,除了以“?”结尾的东西
  • 是的,在 Match 函数中使用子字符串或正则表达式来找到合适的模式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-05
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
相关资源
最近更新 更多